Support » Networking WordPress » Query posts by custom post type and category id

  • Hi,

    how is it possible to query posts by “custom post type” and the “custom post type category”? I would like to get all posts with custom post type “events” and the events-category “sports”.

    My custom post type code:
    http://pastebin.com/n6zDjC08

    I tried something like this using the category ID:

    $args = array('post_type' => 'events','cat'=>35);
    $loop = new WP_Query( $args );

    Or the category slug:

    $args = array('post_type' => 'events','events_category'=>'sports');
    $loop = new WP_Query( $args );

    Both ways are not working 🙁
    Any ideas?
    Thx!

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator Ipstenu (Mika Epstein)

    (@ipstenu)

    🏳️‍🌈 Halfelf Rogue & Plugin Review Team Rep

    Are you trying to search multiple sites, or is this a generic WP question?

    Its on a multisite Installation. Bevor i try to query the posts i use switch_to_blog() to switch to the target blog:

    global $switched;
    switch_to_blog(2);
    
    // Here we go with the problem query
    $args = array('post_type' => 'events','cat'=>35);
    $loop = new WP_Query( $args );
    
    while ( $loop->have_posts() ) : $loop->the_post();
     // DO SOMETHING
    endwhile;
    
    wp_reset_query();
    restore_current_blog();

    But maybe this question would fit to the “How-To and Troubleshooting” section?

    Moderator Ipstenu (Mika Epstein)

    (@ipstenu)

    🏳️‍🌈 Halfelf Rogue & Plugin Review Team Rep

    Okay so you’re trying to search a different site’s posts?

    That is, you’re on siteA and you want posts from SiteB?

    Yes, but i have no problem querying posts from the other blog.

    The switch_to_blog() function works perfect to change the blog and query posts by post_type works fine also:

    $args = array('post_type' => 'events');
    $loop = new WP_Query( $args );

    The only thing which is not working is to add the post_type category-ID to the query:

    $args = array('post_type' => 'events','cat'=>CATEGORY_ID);
    $loop = new WP_Query( $args );

    It seems, that the “cat” parameter is only working for standard categories right? Is it not for custom post_type categories?

    Hi there,
    In case anyone will hit this page in the future,
    I strugled with this type of query and what I see here I think could be fix by using ‘tax_query’ insted of ‘cat’. IF using a custom post type you will also probably have to use a custom taxonomy, if you have access to the database you can verify this in wp_term_taxonomy(if you are not a theme developer).
    More info about custom taxonomy parameters you can find here.
    Regards

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Query posts by custom post type and category id’ is closed to new replies.