1

I followed this tutorial to add colors to categories. However I can't make it work, when I try to use it in my loop nothing happens, I tried multiple versions but none was right. This is what I tried:

<?php
$args = array(
    'post_type' => 'post'
);

$post_query = new WP_Query($args);

if($post_query->have_posts() ) {
    while($post_query->have_posts() ) {
        $post_query->the_post();
        ?>
        
        <div class="catalogue_item">
            <h2 style="color:<?php
                //This is where i want the category color name
                ;
            ?>"><?php the_title(); ?></h2>
            <a href="<?php echo get_permalink(); ?>">lien vers la fiche</a>
            <p>
                <?php foreach ( ( get_the_category() ) as $category ) {
                    echo $category->cat_name . ' ';
                }?>
            </p>
            <?php the_excerpt(); ?>
            <?php the_content(); ?>
            <p> prix: <?php echo (types_render_field( 'price', array() ));?> </p>
            <p> prix2: <?php echo (types_render_field( 'pricet', array() ));?> </p>
        </div>
        <?php
        }
    }
?>

And I cannot find something that works, I'm sorry if this is a dumb one but I am stuck.

0

From your question, it seems that you want to fetch the meta for the post. In which case you would want get_post_meta which would look something like this:

echo get_post_meta( get_the_ID(), 'color', true );

Change the second value ('color') to whatever you have used for the meta key - I took a wild guess.

3
  • I did not work, after many attempts to understand how to retrieve the term_id and the custom field I ended up with that <?php $color_cat = the_category_ID($echo = false); ?> <div class="catalogue_item"> <h2 style="background-color:<?php echo get_term_meta( $color_cat, 'cat_color', true ); ?>"><?php the_title(); ?></h2> I know it's not clean code but it works... Ty for your help Jan 10 at 19:06
  • Ah, I see what the problem is with my answer. You are storing the colour in the term meta, not the post meta. Jan 11 at 23:25
  • Indeed but even with get_term_meta it did not work. Maybe an error I made somewhere else... Jan 13 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.