0

I have a page I'm setting up with various sections to display posts. I want the majority of the page to be user-editable, so I'm filling the sections using a shortcode I wrote. Example:

This:

[diversecity section="sounds-flavors" ids=""]

becomes this:

$qs = new WP_Query(
    array(
        'posts_per_page' => 3,
        'category_name' => 'sounds-flavors'
    )
);

and returns 3 posts from the "Sounds & Flavors" category.

However, the users want to be able to highlight certain articles in each section, so I added the ids variable in the shortcode. The idea is that users can put in a comma-separated list of IDs, and that those posts will be prepended to the category list.

This:

[diversecity section="sounds-flavors" ids="12345,12678"]

becomes this:

$qs = new WP_Query(
    array(
        'posts_per_page' => 3,
        'category_name' => 'sounds-flavors',
        'post__in' => array(12345,12678)
    )
);

but only returns the two posts specified. The desired output is this:

<article id="12345">{First ID Specified}</article>
<article id="12678">{Second ID Specified}</article>
<article id="12980">{Most Recent Post from the Sounds & Flavors category}</article>

I know I can do two queries (one for the specified posts, and for any category posts to fill the remainder, but is it possible to do it in one using WP_Query?

I'm essentially trying to mimic the behavior of sticky posts, so it should technically be possible. Any ideas?

1 Answer 1

0

You should use a custom select query:

$querystr = "
SELECT * FROM $wpdb->posts
LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
WHERE ($wpdb->terms.name = 'sounds-flavors' OR $wpdb->posts.ID IN(12345,12678))
AND $wpdb->term_taxonomy.taxonomy = 'category'
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->posts.post_type = 'post'
LIMIT 3
";

Take a look here: https://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query Regards

1
  • Thank you for weighing in Francisco. I've been experimenting with a custom query, but I haven't been able to get predictable results, either in the ordering of the articles, or the articles being pulled. Jan 20, 2017 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.