I have created a custom post “company” and custom category “company category”. I have a question here, I want to hide child category post in primary category.
For Example:
- Primary Category “First”
- Sub Category “Second”
I’ve created two posts “Fname” and “Sname”. “Fname” was assign to First category and “Sname” assign to Second Category. I don’t want show “Sname” in First category but just “Fname” be display on First category.
Is this possible?
I found a plugin solutions, Just One Category,
But all of them are used for normal post type , not custom post type.
I try edit the code like this:
$q_args = array(
'paged' => $glocal_search_pageds,
'post_type' => array('company'),
's' => $s,
'company_category' => $company_category,
'posts_per_page' => $companyprp,
'orderby' => $orderby,
'order' => $order,
'tax_query' => array(
array(
'include_children' => false
)
)
);
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
I think that the best solution is to hook into the pre_get_posts action hook. First, it is checked if we are in an archive of your custom taxonomy, then set include_children to false for the tax_query argument of the query.
add_action( 'pre_get_posts', 'cyb_pre_get_posts' );
function cyb_pre_get_posts( $query ) {
//Assuming the slug of the custom taxonomy is company-category
//change it with the correct value if needed
if( $query->is_tax( 'company-category' ) && $query->is_main_query() && !is_admin() ) {
$tax_query = array(
array(
'taxonomy' => 'company-category',
'terms' => $query->get( 'company-category' ),
'include_children' => false
);
$query->set( 'tax_query', $tax_query );
}
}
Another approach that seems better (taken from this answer and adapted for custom taxonomy instead of core category taxonomy):
add_filter( 'parse_tax_query', 'cyb_do_not_include_children_in_company_category_archive' );
function cyb_do_not_include_children_in_company_category_archive( $query ) {
if (
! is_admin()
&& $query->is_main_query()
&& $query->is_tax( 'company-category' )
) {
$query->tax_query->queries[0]['include_children'] = 0;
}
}
For custom queries and secondary loops (see WP_Query):
$args = array(
//Rest of you args go here
'tax_query' => array(
array(
'include_children' => false
)
)
);
$query = new WP_Query( $args );
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