• Hi there,

    I have managed to add the advert category to the listings body class using the following code

    function add_category_name($classes = '') {
            $category_id = get_queried_object_id(); 
               $category = get_term( $category_id );
               $classes[] = 'category-'.$category->slug; 
          
            return $classes;
         }
         add_filter('body_class','add_category_name');

    But it doesn’t work on single ad pages – can anyone help?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Author Greg Winiarski

    (@gwin)

    Hi,
    when you are viewing the Ad details page this code get_queried_object_id(); will return the ID of the Advert not category.

    You will need to check if the current page is a singular page and in this case, get the category slug differently

    
    if(is_singular('advert')) {
      $terms = wp_get_post_terms( get_the_ID(), "advert_category" );
      foreach( $terms as $term ) {
        $classes[] = sprintf( "category-%s", $term->slug );
      }
    } else {
      // your code here
    }
    

    I did not test the code as I am not using my dev machine right now, but the general idea on how to get the slugs should be correct.

    Thread Starter twdtony

    (@twdtony)

    Thanks Greg and sorry for the slow reply…

    Another quick question (sorry) how can you get only parent categories with that code?

    Plugin Author Greg Winiarski

    (@gwin)

    Hi,
    the wp_post_terms() function accepts a third param that allows filtering the results the same way WP_Query does https://developer.www.ads-software.com/reference/functions/wp_get_post_terms/, so in this case to show only the top categories you would need to change the line with wp_post_terms() function to

    
    $terms = wp_get_post_terms( get_the_ID(), "advert_category", array( "parent" => 0 ) );
    
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Add category name to single advert page body class’ is closed to new replies.