問題描述

不知道如何實現這一點。我正在嘗試在網站主頁上混合標準的帖子和自定義帖子,但我只想顯示定製帖子,如果設置了元值。顯示帖子工作正常'post_type' => array('game', 'post'),但是當我添加到 meta_query 中,常規帖子不再顯示 (這是有道理的,因為它們不符合 meta_query 條件) 。

那麼如何將 meta_query 限制為僅定製的帖子類型,以便常規帖子仍然包含在內?

最佳解決方案

有不同的做法,2 進入我的腦海:

  1. 使用完整的自定義 $wpdb 查詢

  2. 使用 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'];
  }
}

查看內聯評論進一步解釋。

還可以查看 WP_Meta_Query on Codex 以獲取有關如何設置元查詢 args 的完整文檔。


Edit

我在一個可重用的插件中重構代碼,使用一個類。作為 Gist 。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。