Advertisement
Guest User

Ignore post by meta value in the main query

a guest
Mar 8th, 2016
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.53 KB | None | 0 0
  1. add_filter( 'posts_results', 'insert_post_wpse_96347', 10, 2 );
  2. function insert_post_wpse_96347( $posts, \WP_Query $q ) {
  3.     remove_filter( current_filter(), __FUNCTION__ );
  4.  
  5.     if ( $q->is_main_query() && $q->is_home() && 0 == get_query_var( 'paged' ) ) {
  6.  
  7.         $args_uno = [
  8.             'meta_key'                  => 'caja',
  9.             'meta_value'                => 'uno',
  10.             'post__not_in'          => get_option( "sticky_posts" ),
  11.             'posts_per_page'        => '1',
  12.             'status'                        => 'publish',
  13.             'suppress_filters'  => true
  14.         ];
  15.  
  16.         $args_dos = [
  17.             'meta_key'                  => 'caja',
  18.             'meta_value'                => 'dos',
  19.             'post__not_in'          => get_option( "sticky_posts" ),
  20.             'posts_per_page'        => '1',
  21.             'status'                        => 'publish',
  22.             'suppress_filters'  => true
  23.         ];
  24.  
  25.         $p1insert = new WP_Query($args_uno);
  26.         $p2insert = new WP_Query($args_dos);
  27.  
  28.         if ( !empty( $p2insert->posts ) ) {
  29.             array_splice( $posts, 0, 0, $p1insert->posts );
  30.             array_splice( $posts, 1, 0, $p2insert->posts );
  31.         }
  32.     }
  33.     return $posts;
  34. }
  35.  
  36. function cmp_exclude_featured_posts($query) {
  37.     $exclude = array();  //Create empty array for post ids to exclude
  38.     if ( $query->is_main_query() && $query->is_home()) {
  39.  
  40.             $featured = get_posts(array(
  41.                 'post_type'     => 'post',
  42.                 'posts_per_page'    => 2,
  43.                 'meta_query'    => array(
  44.                     array(
  45.                         'key'           => 'caja',
  46.                         'value'     => array('uno','dos')
  47.                     ),
  48.                 ),
  49.             ));
  50.  
  51.             foreach($featured as $hide) {
  52.                 $exclude[] = $hide->ID;
  53.             }  
  54.  
  55.             $query->set('post__not_in', $exclude);
  56.         }
  57. }
  58.  
  59. add_filter( 'pre_get_posts', 'cmp_exclude_featured_posts' );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement