3

I have an CPT archive page that I would like to exclude certain posts from if a field is null. The field I want to look for is title_group and I am already using a different meta_key to order the results with. I am not sure how to use a second key to exclude posts. Thanks for looking!

function set_posts_per_page_for_attorneys_cpt( $atty ) {
  if ( !is_admin() && $atty->is_main_query() && is_post_type_archive( 'attorneys' ) ) {
    $atty->set( 'posts_per_page', '-1' );
    $atty->set( 'meta_key', 'last_name' );
    $atty->set( 'orderby', 'meta_value' );
    $atty->set( 'order', 'ASC' );
    $atty->set( 'facetwp', true);
  }
}
add_action( 'pre_get_posts', 'set_posts_per_page_for_attorneys_cpt' );
2
  • 2
    Sounds like a case for meta_query. If you follow this link and scroll down to Multiple Custom Field Handling you can see some examples.
    – Howdy_McGee
    Mar 19, 2018 at 19:55
  • Thanks – that got me in the right direction. Had to do a little more digging to resolve it fully. I've posted the answer for others to see.
    – Al Avery
    Mar 21, 2018 at 16:54

1 Answer 1

0

@Howdy_McGee – Thanks for pointing me in the right direction. Below is the code I used. By the way, I know that the FacetWP plugin can be a little particular with queries. In case anyone is wondering, this works with it.

function set_posts_per_page_for_attorneys_cpt( $atty ) {
  if ( !is_admin() && $atty->is_main_query() && is_post_type_archive( 'attorneys' ) ) {

  $meta_query = array(array(
    'key'=>'last_name',
  ));

  $meta_query = $atty->get('meta_query');

  //filter out people without a particular key
  $meta_query = array(array(
    'key'=>'title_group',
    'value'=>'',
    'compare'=>'!=',
  ));

  //update the query
  $atty->set( 'orderby', $meta_key);
  $atty->set( 'order', 'ASC' );
  $atty->set( 'meta_query',$meta_query );
  $atty->set( 'posts_per_page', '-1' );
  $atty->set( 'facetwp', true);
  }
}
add_action( 'pre_get_posts', 'set_posts_per_page_for_attorneys_cpt' );
2
  • While this is working, I also need the posts to sort ASC by 'last_name'. I think I have overlapping meta_querys, but not sure how to resolve it...
    – Al Avery
    Apr 3, 2018 at 2:53
  • Actually, I need to sort by two meta keys: 'last_name', then 'first_name'…
    – Al Avery
    Apr 3, 2018 at 20:37

Your Answer

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

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