• Hi Everyone,
    I am trying to exclude categories from a blog page, I have got a snippet for my functions file

    
    function exclude_category( $query ) {
    if ( $query->is_page( 6127 ) && $query->is_main_query() ) {
    $query->set( 'cat', '-16, -17, -18, -344, -19, -25, -209' );
    }
    }
    add_action( 'pre_get_posts', 'exclude_category' );
    

    It seems to return a blank white page ??

    Thanks

    Rockyuk

    • This topic was modified 6 years, 3 months ago by Jose Castaneda. Reason: added backticks to code
Viewing 6 replies - 1 through 6 (of 6 total)
  • Moderator Samuel Wood (Otto)

    (@otto42)

    www.remarpro.com Admin

    Posts are not displayed on pages, so why are you checking for is_page()?

    Try is_home() instead. The blog page is always “home”.

    As for a blank white page, you have a typo somewhere. Turn on WP_DEBUG to see the error message and to find it.

    You might need to use a different check, like:
    if ( $query->is_home() && $query->is_main_query() && ! is_admin() )

    You could try dumping the $query variable to see what it has set.
    Also, the other way to exclude categories is category__not_in, but it takes an array parameter I think.

    Thread Starter Rockyuk

    (@rockyuk)

    Hi Samuel,
    I have posts displayed on specific pages via shortcodes but it want those pages to only display specific categories not all of them.

    Thanks

    Rockyuk

    Ah, you said “blog page”. If it is a shortcode, then it is not is_main_query.

    Moderator bcworkz

    (@bcworkz)

    I’m assuming the shortcode handler is executing its own query to determine what content to return. In such a case, is_main_query is not applicable like Joy says. Also is_page( 6127 ) is not applicable either. There is likely some combination of query vars that will uniquely identify the query from the shortcode. Try doing print_r( $query->query_vars ); from you callback, outside of any conditional. You will get a variety lists, try to discern which one is due to the shortcode. Then identify which set of query vars uniquely identify this query. Check these values in your conditional statement.

    Another option is to alter the shortcode handler’s query directly in the declaration and add your category restrictions to the instantiation of the query.

    Another option is to create a custom template for just pages which need the restrictions. Add your action callback just before the Loop code and remove it just after the loop. The category restrictions will then only be applied to shortcode queries done within the loop.

    Thread Starter Rockyuk

    (@rockyuk)

    Ok, thank you i will try this and update. Thank you Joy and bcworkz

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Exclude Category From Blog Page’ is closed to new replies.