mgblahblah
Forum Replies Created
-
Forum: Hacks
In reply to: Sticky Post functionality with WP_Query is ignored when using AJAXI figured it out lol
After doing a lot of googling to no success, the following post gave me an idea:
In it, it mentions that WP_Query checks the following before sorting Sticky Posts at the top:
if ( $this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts'] ) {Because I was running my query in a function independently called by AJAX, there was no Post or Page ID associated with this particular snippet of code. Therefore, WP_Query could not fulfill its conditional in order to do its default sticky_post function.
“get_posts” does not allow for sticky posts to show on top as it automatically sets “ignore_sticky_posts” to true.
Check out the WP Developers Page for get_posts (https://developer.wordpress.org/reference/functions/get_posts/). On line 1591 of the code snippet, you will see:
$r['ignore_sticky_posts'] = true;being explicitly set right before the query is returned.
So, we can neither use WP_Query nor get_posts in this particular instance.
My solution was to do the following:
// get_posts of all the possible posts, with your desired parameters and post-per-page set to -1 $all_posts = get_posts( $args ); // check if there are any sticky posts $sticky = get_option( 'sticky_posts' ); // there are sticky posts, do this psuedo-code if ( is_array($sticky) && !empty($sticky) ) { // do a get_post query for ONLY the sticky posts posts that are in your desired $args array $args['post__in'] = $sticky; $sticky_posts = get_posts( $args ); // merge $total_stories_id into the end of $sticky $merged = array_merge( $sticky_posts, $all_posts ); // remove duplicates and re-indexes $array = array_values( array_unique( $merged ) ); // return a slice of X elements, starting at the $offset location $return_array = array_slice( $array , [calculated post offset], [your desired post-per-page] ); } else { // else, do wordpress default (wp_query or get_posts, it doesn't matter) $return_array = get_posts( $args ); }For the sake of cutting down the array sizes being passed about, I did:
wp_list_pluck( [array], 'ID' );on the 2 get_posts arrays. You don’t have to do this, it really depends on what kind of data you are passing back via AJAX.
I hope this helps anyone else!