• Resolved Kirk Wight

    (@kwight)


    I’m not sure how best to go about this query.

    I have a custom post type (Issues) with connected Articles (another cpt). Connections are all working fine.

    The front page of this online magazine needs to pull random Articles, but only from those connected to the Issue categorized ‘current’.

    I have no problem with querying the Articles with WP_Query, nor getting the current Issue; it’s combining them that I can’t figure out.

    Any ideas?

    http://wordpress.org/extend/plugins/posts-to-posts/

Viewing 7 replies - 1 through 7 (of 7 total)
  • Plugin Author scribu

    (@scribu)

    You can do it in two steps:

    1. Get all the IDs of the issues categorized ‘current’:

    $issue_ids = get_posts( array(
      'fields' => 'ids',
      'post_type' => 'issue',
      'category_name' => 'current',
      'nopaging' => true
    ) );

    2. Get the articles connected to those issues:

    $articles = new WP_Query( array(
      'connected_type' => 'YOUR_CONNECTION_TYPE',
      'connected_items' => $issue_ids,
      'orderby' => 'rand',
      'posts_per_page' => 1
    ) );
    Plugin Author scribu

    (@scribu)

    Maybe something like this would be nice to have:

    $articles = new WP_Query( array(
      'connected_type' => 'YOUR_CONNECTION_TYPE',
      'connected_query' => array(
        'category_name' => 'current',
      ),
      'orderby' => 'rand',
      'posts_per_page' => 1
    ) );
    Thread Starter Kirk Wight

    (@kwight)

    That worked perfectly, thanks!

    Yes, your ‘connected_query’ would be great; it would avoid two separate queries when all you want is a quick piece of data to set a variable.

    Thanks again!

    sorry my english is very bad

    I’m not getting with this code, could post the full code.

    Thank you.

    (@disonancias)

    I just asked how to do it with custom taxonomies, but found out right after posting. In case anyone else needs it:

    $articles = new WP_Query( array(
      'connected_type' => 'YOUR_CONNECTION_TYPE',
      'my_custom_taxonomy' => 'my_custom_term',
      'orderby' => 'rand',
      'posts_per_page' => 1
    ) );

    Hi there, I am trying to do the same thing. The code above works well, but I am getting duplicate records. Is there a way to remove duplicates via a “distinct” or something? Thanks!

    I am posting my code below …

    $originals = query_posts( array(
    ‘fields’ => ‘ids’,
    ‘post_type’ => ‘original’,
    ‘mediacategory’ => ‘fine-arts’
    ) );

    $artists = new WP_Query( array(
    ‘connected_type’ => ‘artist_to_original’,
    ‘connected_items’ => $originals
    ) );

    If an artist has created multiple originals in the category, they are showing up multiple times in my results.

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘[Plugin: Posts 2 Posts] WP_Query results based on category of connected post’ is closed to new replies.