Skip to content

Instantly share code, notes, and snippets.

@carlodaniele
Last active November 6, 2022 10:36
Show Gist options
  • Save carlodaniele/616a1348f0a6fd25c92a to your computer and use it in GitHub Desktop.
Save carlodaniele/616a1348f0a6fd25c92a to your computer and use it in GitHub Desktop.
Build a custom query with pre_get_posts
<?php
/**
* Build a custom query
*
* @param $query obj The WP_Query instance (passed by reference)
*
* @link https://codex.wordpress.org/Class_Reference/WP_Query
* @link https://codex.wordpress.org/Class_Reference/WP_Meta_Query
* @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;
}
$meta_query = array();
// add meta_query elements
if( !empty( get_query_var( 'key1' ) ) ){
$meta_query[] = array( 'key' => 'key1', 'value' => get_query_var( 'key1' ), 'compare' => 'LIKE' );
}
if( !empty( get_query_var( 'key2' ) ) ){
$meta_query[] = array( 'key' => 'key2', 'value' => get_query_var( 'key2' ), '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 );
@Yorlinq
Copy link

Yorlinq commented Nov 6, 2022

Hi there, thanks for this great peace of code.

Perhaps you can help me out with an issue regarding your code...

https://stackoverflow.com/questions/74335018/pre-get-posts-with-meta-query-effects-static-pages-in-woocommerce

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment