0

How do I display a custom content using the in_category though using the parent category as a parameter and just selecting the subcategory on that category.

On my post I didn't select the parent category so that it displays the permalink like /%category%/%postname%/ if I select the parent and the subcategory it will not show the subcategory on the permalinks which is required. if this is possible by just manipulating the permalink in the general settings it will also do the job.

Category

  • Subcategory 1

  • Subcategory 2

  • Subcategory 3

CODE:

   <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
        <article>
            <section>
                <?php if (in_category('category')) { ?>     
                    <?php the_content(); ?>
                <?php } ?>
            </section>
        </article> 
    <?php endwhile; ?>          
    <?php else : ?>
    <?php endif; ?>
0

in_category() accepts an array of categories to check against. So if you can get a list of all child categories for the parent category you want to check you can use that to see if your post is in any of those.

You can do this by using get_categories() and specifying the parent. This will get all categories who are direct children of the given category. If you also specify fields as ids you can just get their IDs, which will work better for in_category():

<?php
$categories = get_categories( array(
    'parent' => 123,
    'fields' => 'ids',
) );

if ( in_category( $categories ) ) : ?>
    // Content here
<?php endif; ?>

If you only have the slug of the parent category, you'll need to use get_term_by() to get the ID for use as the parent argument:

<?php
$parent = get_term_by( 'slug', 'category-slug', 'category' );

$categories = get_categories( array(
    'parent' => $parent->term_id,
    'fields' => 'ids',
) );

if ( in_category( $categories ) ) : ?>
    // Content here
<?php endif; ?>
  • is it possible to just get the parent category of the current category of the post and set it in the argument? For the second code do i need replace the arrays inside the get_term_by? – MIke Mar 7 '18 at 6:59
  • In the second piece of code replace category-slug with the slug of your category. The 3rd argument needs to literally be 'category'. – Jacob Peattie Mar 7 '18 at 7:22
  • Regarding your first question, why? You would just be checking "Am I in a category that is a child of its parent?". It would always be true. – Jacob Peattie Mar 7 '18 at 7:23

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.