wp query – custom post type and a “sticky” position taxonomy

Question

I have a custom post type with a custom taxonomy that denotes various types of places the custom post might appear in the site. One that I’m having some trouble with is a “sticky” term for the archive pages. Essentially it should act as you might expect the standard sticky post feature to act on archive pages for this specific custom post type. I’m still trying to work out the best option, but I have this so far.

function sticky_posts( $posts, $query ) {
  if ( is_post_type_archive( 'custom-post' ) && $query->is_main_query() && ! is_admin() ) {

    $args = array(
      'post_type' => 'custom-post',
      'post_status' => 'publish',
      'tax_query' => array(
          array(
              'taxonomy' => 'position',
              'field'    => 'slug',
              'terms'    => 'sticky',
          )
      )
  );

  $sticky_posts = new WP_Query( $args );

  foreach( $sticky_posts->posts as $post ) {
    $position = array_search( $post->ID,  wp_list_pluck( $posts, 'ID' ), true );
    $candidate = $posts[ $position ];
    unset( $posts[ $position ] );
    array_unshift( $posts, $candidate );
  }

  }

  return $posts;
}

add_filter( 'posts_results', 'sticky_posts');

This doesn’t quite work right, as the posts_results hook doesn’t quite give you everything that this. (I’m not entirely convinced the function actually does what I want but it’s what I’ve got so far.) Suggestions for a better implementation?

0
jshwlkr 5 months 2021-05-19T14:16:35-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse