Support

Account

Home Forums Front-end Issues Displaying stuff depending on categories Reply To: Displaying stuff depending on categories

  • This isn’t strictly speaking an ACF question, and more of a WP core question. Depending on how you’ve set up your site will depend on the particular code that you’ll need.

    Getting WP categories is relatively easy, and if you have set each of these up as a normal Post within WordPress, then you can use a combination of the function in_category() to check if the current post is in the specified category, and cat_is_ancestor_of() to check if that category is a sub-category of the parent.

    In practice this would look something like:

    <?php
    
    global $post;
    
    // Get categories applied to post
    $categories = get_the_category($post->ID)
    
    // Retrieve the first category ID (just in case multiple selected)
    $current_category = $categories[0]->term_id;
    
    // If this post is in the category Books, or a child-category of Books
    if( in_category('books') || cat_is_ancestor_of('books', $current_category) ) {
    	// Get the template part from acffields/acf-books.php
    	get_template_part('acffields/acf','books');
    }
    elseif( in_category('films') || cat_is_ancestor_of('films', $current_category) ){
    	// Get the template part from acffields/acf-films.php
    	get_template_part('acffields/acf','films');
    }
    else{
    	// If you want to put something else in if no category selected, add it in here.
    }
    
    ?>

    If you have set your posts up as a Custom Post Type with a custom taxonomy – then this won’t work, and you’ll need to use get_post_terms() instead, and then do an alternate check to confirm if that post is within that post category.

    You can alter this to the actual names of the categories, and add / remove any as necessary. Hopefully this will help give you a good starting point.