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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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' );
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0