web-dev-qa-db-ja.com

コンテンツに二次ループが含まれているページのIDを取得します

ショートコードを使用して、そのコンテンツ内に別のCPTのループがあるページのID(ループ外)を取得しようとしています。

get_queried_object()print_rを実行すると、CPTの登録に使用された引数がすべて得られます。
もし私がecho$post->IDならば、二次ループの最後の項目のIDを取得します。
私がechoget_queried_object_id()であれば、私は常に0を受け取ります。

これが私が現在使っているコードです。

function get_meta_values() {
    global $post;
    $queried_object = get_queried_object();
    echo '<pre>';
    print_r( $queried_object ); //Returns args used to register the CPT
    echo '<br> $queried_object->ID: ' . $queried_object->ID; //Returns Nothing
    echo '<br>get_queried_object_id(): '. get_queried_object_id(); // Returns 0 all the time
    echo.'<br>PageID: ' . $post->ID; // Returns the ID of last item in the secondary loop
    echo '</pre>';

}
add_action( 'wp_footer', 'get_meta_values' );  

私の目標は、ページのID(ショートコードがある場所)を取得して、いくつかのカスタムフィールド値を取得することです。

編集:私はWooCommerceを使用していますが、商品を出力するショートコードはカスタムです。私は私が他の方法で問題を回避できることを知っていますが、これがうまくいかない理由だけで興味があります。

4
Abhik

他の人がすでに考え出しているように:もしあなたがカスタムクエリを持つサードパーティのプラグインを持っているなら、あなたは悪い日を過ごすでしょう!

1つの解決策はあなたの結果をキャッシュすることかもしれません。

テンプレート(例:page.php)

while (have_posts()): the_post();
    global $my_cached_data;
    $post_id = get_the_ID();
    /* 
     * If you have single meta keys, this array_map function 
     * makes them easy to access; otherwise just use:
     *
     * $my_cached_data[$post_id] = get_post_meta( $post_id) 
     */
    $my_cached_data[$post_id] = array_map( 
        function( $a )
        { 
            return $a[0]; 
        }, 
        get_post_meta( $post_id) 
    );
endwhile;

footer.php

global $my_cached_data;
echo "<pre>".print_r($my_cached_data, true)."</pre>";

考えられる結果(ページID 2と15では同じ投稿メタデータを持つ)

array(2) {
  [2]=>
  array(2) {
        ["meta_key"]=>
    string(10) "meta_value"
        ["another_key"]=>
    string(10) "meta_value"
  }
  [15]=>
  array(2) {
        ["meta_key"]=>
    string(10) "meta_value"
        ["another_key"]=>
    string(10) "meta_value"
  }
}
1
iantsch