• Resolved davao1

    (@davao1)


    Hello , I want to hide the post from subcategory in the main category but I can’t find the way.
    for example if someone visit my main category I don’t want him to see the posts of all the sub categories in the main category post list.
    or I must create different category for each subject?

    Main is (ArabNews) sub (KSA news , Jordan News , Syria news ) so i don’t want to show the posts from (KSA news) in Arab news..

    is that possible? Thanks in advance for your time and help

Viewing 3 replies - 1 through 3 (of 3 total)
  • swayam.tejwani

    (@swayamtejwani)

    You can hide subcategories using this code in functions.php of your theme

    
    function wpse_filter_child_cats( $query ) {
    
    if ( $query->is_category ) {
        $queried_object = get_queried_object();
        $child_cats = (array) get_term_children( $queried_object->term_id, 'category' );
    
        if ( ! $query->is_admin )
            //exclude the posts in child categories
            $query->set( 'category__not_in', array_merge( $child_cats ) );
        }
    
        return $query;
    }
    add_filter( 'pre_get_posts', 'wpse_filter_child_cats' );

    `

    Let me know if it works

    Carlos Bravo

    (@cbravobernal)

    Hi @davao1 !

    You could use a PHP Code Snippet plugin and add create a filter in the pre_get_posts:

    
    add_action('pre_get_posts', 'filter_out_children');
    
    function filter_out_children( $query ) {
      if ( is_main_query() && is_category() && ! is_admin() ) {
         $qo = $query->get_queried_object();
         $tax_query = array(
           'taxonomy' => 'category',
           'field' => 'id',
           'terms' => ! is_null($qo) ? $qo->term_id : null,
           'include_children' => false
         );
         $query->set( 'tax_query', array($tax_query) );
      }
    }

    Hope it helps!

    Thread Starter davao1

    (@davao1)

    wow ,, many many many thanks … yes it’s worked very well ..

    really you help me so much ..

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Hide posts in subcategory’ is closed to new replies.