Skip to content

Instantly share code, notes, and snippets.

@carlodaniele
Created March 16, 2016 20:28
Show Gist options
  • Save carlodaniele/93611e9769e27f894af6 to your computer and use it in GitHub Desktop.
Save carlodaniele/93611e9769e27f894af6 to your computer and use it in GitHub Desktop.
Build a custom meta query
<?php
/**
* Build a custom query
*
* @param $query obj The WP_Query instance (passed by reference)
*
* @link https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts
*/
function myplugin_pre_get_posts( $query ) {
// check if the user is requesting an admin page
// or current query is not the main query
if ( is_admin() || ! $query->is_main_query() ){
return;
}
// edit the query only when post type is 'food'
// if it isn't, return
if ( !is_post_type_archive( 'book' ) ){
return;
}
$meta_query = array();
// add meta_query elements
if( !empty( get_query_var( 'book-author' ) ) ){
$meta_query[] = array( 'key' => 'author_surname', 'value' => get_query_var( 'book-author' ), 'compare' => 'LIKE' );
}
if( count( $meta_query ) > 1 ){
$meta_query['relation'] = 'AND';
}
if( count( $meta_query ) > 0 ){
$query->set( 'meta_query', $meta_query );
}
}
add_action( 'pre_get_posts', 'myplugin_pre_get_posts', 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment