Home > Net >  How can I use custom field on categories in wordpress?
How can I use custom field on categories in wordpress?

Time:09-21

I've added a custom field as color-code to my categories, and I want to show the categories of each post with that color code on it. I tried the code below, but it doesn't work in the way I need.

 <div class="blog-post-grids">
      <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        $args = array('post_type' => 'post', 'posts_per_page' => 9, 'paged' => $paged);
         $wp_query = new WP_Query($args);
         while (have_posts()): the_post();?>
         <?php 
          $color = get_field('color-code', the_category());
         ?>
         <figure class="blog-post-cart">
           <div><?php the_post_thumbnail();?></div>
           <figcaption>
              <a href="<?php the_permalink() ?>">
                <h2><?php the_title()?></h2>
              </a>
              <p style="color: <?php echo $color ?>">
               <?php echo the_category(', ')  ?>
              </p>
              <?php the_content(''); ?>
           </figcaption>
         </figure>
        <?php endwhile;?>
    </div>

CodePudding user response:

It depends on the color code type

If it hex add # before,

Or make sure it's in rgb format like rgb(143 98 188)

CodePudding user response:

To do this, you will need the category's ID, as outlined here: https://www.advancedcustomfields.com/resources/adding-fields-taxonomy-term/

Your get_field() would be formatted like this:

$color = get_field('color-code', 'category_123');

Where "123" is the ID of the Category.

Right before the get_field like, add this:

$thisCategory = get_the_category();

$thisCategory will be an array of all of the categories attached to the current post in the loop.

Then replace your $color = get_field() line with this:

$color = get_field('color-code', 'category_'.$thisCategory[0]->term_id);

$thisCategory[0]->term_id will return the category ID of the first category attached to the post.

So to put it all together, this would be the new code:

 <div class="blog-post-grids">
  <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $args = array('post_type' => 'post', 'posts_per_page' => 9, 'paged' => $paged);
     $wp_query = new WP_Query($args);
     while (have_posts()): the_post();?>
     <?php 
      $thisCategory = get_the_category();
      $color = get_field('color-code',  'category_'.$thisCategory[0]->term_id);
     ?>
     <figure class="blog-post-cart">
       <div><?php the_post_thumbnail();?></div>
       <figcaption>
          <a href="<?php the_permalink() ?>">
            <h2><?php the_title()?></h2>
          </a>
          <p style="color: <?php echo $color ?>">
           <?php echo the_category(', ')  ?>
          </p>
          <?php the_content(''); ?>
       </figcaption>
     </figure>
    <?php endwhile;?>
</div>
  • Related