Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing all posts and custom post types by using a single category

I have created a post type with CPT UI:

add_action( 'init', 'cptui_register_my_cpts_matratze' );
function cptui_register_my_cpts_matratze() {
    $labels = array(
        "name" => __( 'Matratzen', '' ),
        "singular_name" => __( 'Matratze', '' ),
        );

    $args = array(
        "label" => __( 'Matratzen', '' ),
        "labels" => $labels,
        "description" => "",
        "public" => true,
        "publicly_queryable" => true,
        "show_ui" => true,
        "show_in_rest" => false,
        "rest_base" => "",
        "has_archive" => true,
        "show_in_menu" => true,
                "exclude_from_search" => false,
        "capability_type" => "post",
        "map_meta_cap" => true,
        "hierarchical" => false,
        "rewrite" => array( "slug" => "matratze", "with_front" => true ),
        "query_var" => true,

        "supports" => array( "title", "editor", "thumbnail", "excerpt", "trackbacks", "custom-fields", "comments", "revisions", "author", "page-attributes", "post-formats" ),      
        "taxonomies" => array( "category", "post_tag" ),
            );
    register_post_type( "matratze", $args );

// End of cptui_register_my_cpts_matratze()
}

However, when I want to access the categories over a link in the my Frontend, I get no posts.

For example when you click on I get nothing back:

Category

The post is on and has the category DaMi:

Post

Is my CPT UI Post Type wrongly configured? Any suggestions what I am doing wrong?

like image 924
Carol.Kar Avatar asked Sep 27 '16 06:09

Carol.Kar


1 Answers

look over here

By default the category pages on your WordPress site will only display the default ‘Posts’ post type, so you need to add your CPT before Wordpress query the posts by adding the pre_get_posts filter.

added code here:

add_filter('pre_get_posts', 'query_post_type');
function query_post_type($query) {
  if( is_category() ) {
    $post_type = get_query_var('post_type');
    if($post_type)
        $post_type = $post_type;
    else
        $post_type = array('nav_menu_item', 'post', 'matratze'); // don't forget nav_menu_item to allow menus to work!
    $query->set('post_type',$post_type);
    return $query;
    }
}
like image 154
Allen Avatar answered Oct 27 '22 00:10

Allen