Archived topic
location rules: "In Category"
5 replies · Started by Dan on March 24, 2022
Hi
Is there an option to set a location rule for a dynamic element to check if it is "In a category" and all their child categories?
I'm creating an archive page which will display posts from a category and also posts from child-categories of that category.
So instead of listing all the child categories of that parent, is there a rule stating: All posts who are in that Parent category (which will include posts in the child categories too).
Thanks
Dan
Hi there,
how is this archive pulling in the parent category and its children?
By default that would mean the a post with a child category has also the parent category selected.
Let me know
The parent category only "houses" the child categories and does nt have posts directly assigned to it.
The posts are assigned to the child categories:
Parent Category
- Child Category A - post 1,2,3
- Child Category B - post 4,5,6
- Child Category c - post 7,8,9
I would like the location rule to include all the posts who are under the Parent category and not state specifically child A, child B, child C, because the child cats can be added and I would not like to change the location rules every time a new child category is created.
Thanks
Dan
Hi Dan,
Try this 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;
}
}
add_filter( 'generate_element_display', function( $display, $element_id ) {
if ( 100 === $element_id && post_is_in_descendant_category( 20 ) ) {
$display = true;
}
return $display;
}, 10, 2 );
Update the 100with your element id, and 20 with your parent category id.
Leave the location of your element blank.
Thanks Ying,
I'll give that a try.
Dan
Let me know :)