Answers:
有两种方法可以解决这个问题,我想到2:
$wpdb
查询WP_Query
带有过滤器,通过WP_Meta_Query
打造更多的SQL我将在这里发布案例2的示例代码
/**
* Run on pre_get_posts and if on home page (look at url)
* add posts_where, posts_join and pre_get_posts hooks
*/
function home_page_game_sql( $query ) {
// exit if is not main query and home index
if ( ! ( $query->is_main_query() && ! is_admin() && is_home() ) ) return;
add_filter( 'posts_where', 'home_page_game_filter' );
add_filter( 'posts_join', 'home_page_game_filter' );
}
add_action('pre_get_posts', 'home_page_game_sql');
/**
* Set the SQL filtering posts_join and posts_where
* use WP_Meta_Query to generate the additional where clause
*/
function home_page_game_filter( $sql = '' ) {
// remove filters
remove_filter( current_filter(), __FUNCTION__);
static $sql_game_filters;
if ( is_null($sql_game_filters) ) {
// SET YOUR META QUERY ARGS HERE
$args = array(
array(
'key' => 'my_custom_key',
'value' => 'value_your_are_looking_for',
'compare' => '='
)
);
$meta_query = new WP_Meta_Query( $args );
$sql_game_filters = $meta_query->get_sql('post', $GLOBALS['wpdb']->posts, 'ID');
}
// SET YOUR CPT NAME HERE
$cpt = 'game';
global $wpdb;
if ( current_filter() === 'posts_where' && isset($sql_game_filters['where']) ) {
$where = "AND ($wpdb->posts.post_status = 'publish') ";
$where .= "AND ( $wpdb->posts.post_type = 'post' OR ( ";
$where .= $wpdb->prepare( "$wpdb->posts.post_type = %s", $cpt);
$where .= $sql_game_filters['where'] . ' ) )';
$where .= " GROUP BY $wpdb->posts.ID ";
return $where;
}
if ( current_filter() === 'posts_join' && isset($sql_game_filters['join']) ) {
return $sql .= $sql_game_filters['join'];
}
}
请参阅内联注释以获取进一步的解释。
另请参阅Codex上的WP_Meta_Query,以获取有关如何设置元查询参数的完整文档。
我使用一个类在可重用的插件中重构了代码。可作为要点。
WP_Query
。您将需要使用pre_get_posts
alter query或自定义SQL语句。无论如何,请显示您的当前代码。