Question

I am trying to insert a "style" in single page of a category and its child categories.

.relatednews{display:none}.

I inserted the following code in functions.php of Child Theme, but it didn't work.

......................................................................

function post_is_in_descendant_category(){
if ( ! function_exists( 'post_is_in_descendant_category' ) ) {
    function post_is_in_descendant_category( $cats, $_post = null ) {
        foreach ( (array) $cats as $cat ) {
            // get_term_children() accepts integer ID only
            $descendants = get_term_children( (int) $cat, 'category' );
            if ( $descendants && in_category( $descendants, $_post ) )
                return true;
        }
        return false;
    }
}
}
function hiderelated(){
if ( in_category( 168 ) || post_is_in_descendant_category( 168 ) ) {
   ?><style>.relatednews{display:none}</style><?php
}
}
add_action( 'wp', 'hiderelated' );

......................................................................

HELP ME! I need help to make this style work in categories 168 and its descendant categories?

Was it helpful?

Solution

A few changes to your code:

  • Changed the action hook to wp_head.
  • Removed the false 'pluggable' wrapping of your function.

if ( ! function_exists( 'post_is_in_descendant_category' ) ) {
    function post_is_in_descendant_category( $cats, $_post = null ) {
        foreach ( (array) $cats as $cat ) {
            // get_term_children() accepts integer ID only
            $descendants = get_term_children( (int) $cat, 'category' );
            if ( $descendants && in_category( $descendants, $_post ) )
                return true;
        }
        return false;
    }
}

function hiderelated(){
  if ( in_category( 168 ) || post_is_in_descendant_category( 168 ) ) {
  ?>
  <style>
    .relatednews { display: none; }
  </style>
  <?php
  }
}
add_action( 'wp_head', 'hiderelated' );
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top