Last active
November 6, 2022 10:36
-
-
Save carlodaniele/616a1348f0a6fd25c92a to your computer and use it in GitHub Desktop.
Build a custom query with pre_get_posts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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