Jump to content

Use PHP Variable as Value for Inline Style Property


Recommended Posts

I've tried everything but cannot get this to work :


$cats = str_replace( '<a', '<a style="color: ' . $cat_color . ' "', get_the_category_list( ', ' ), $cats );

This doesn't work either :

$cats = str_replace( '<a', '<a style="color:{$cat_color}"', get_the_category_list( ', ' ), $cats );

The result i get is this :


element.style {

color: ($color);



Edited by braddalton
Link to comment
Share on other sites

Works great when posts only contain 1 category link. Thanks.

The only problem i have now is the value for the first category is used to style every category link when the post contains more than 1 category.

$category_id = get_the_category( get_the_ID());
$cat_id      = get_category($category_id[0]->term_id);

$color = get_field( 'cat_color', $cat_id );

$cats = str_replace( '<a', "<a style='color:$color'", $list );

Should i start a new thread for this 2nd problem

Edited by braddalton
Link to comment
Share on other sites

Yes, my problem is i can't work out how to use the value foreach custom field to color each category link when the post is assigned to multiple categories.

I think i need to use a foreach loop with an indexed Array with the category id foreach value returned as a string.

Or an associative Array so i can assign a category id foreach custom field value and return an array of colors which returns this array on the first post in the loop

array (size=4) 'red' => int 0 'green' => int 0 'blue' => int 0 'alpha' => float 1

And this on the 2nd 

array ()
  'red' => int 221
  'green' => int 153
  'blue' => int 51
  'alpha' => float 1


    $list = get_the_category_list();

    $category_id = get_the_category( get_the_ID());
    $id          = get_category($category_id[0]->term_id);

    $color       = get_field( 'cat_color', $id );
    foreach( $id as $color ) {

    $cats = str_replace( '<a', "<a style='color:$color'", $list );


Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.