【问题标题】:How can I get all pages that contain the same meta key?如何获取包含相同元键的所有页面?
【发布时间】:2016-12-02 00:25:57
【问题描述】:

我想获取所有包含元键“basePrice”的 Wordpress 页面,而不考虑元值。

当我尝试做一个简单的get_pages() 时,会返回一个空数组。 根据 Wordpress 文档,它指出 meta_value 需要 meta_key 才能工作,但反过来不行,所以它应该工作?

$basePrices = get_pages(array(
    'meta_key' => 'basePrice'
));

如何在我的数组中获取所有具有名为“basePrice”的元键的页面?

【问题讨论】:

    标签: wordpress meta-key


    【解决方案1】:

    首先,您应该为这些复杂的查询使用 WordPress 查询对象。这会给你更多的论据。

    所以你可以这样做:

    // Let's prepare our query:
    $args = array(
       'post_type' => 'page',
       'posts_per_page' => -1,
       'meta_query' => array(
            array(
               'key' => 'basePrice',
               'compare' => 'EXISTS'
            ),
       )
    );
    $the_query = new WP_Query( $args );
    
    // Array to save our matchs:
    $pages = array();
    
    // The Loop
    if ( $the_query->have_posts() ) {
    
        while ( $the_query->have_posts() ) {
    
             // Let's take what we need, here the whole object but you can pick only what you need:
             $pages[] = $the_query->the_post();
    
        }
    
        // Reset our postdata:
        wp_reset_postdata();
    }
    

    这应该可以正常工作。

    使用get_pages() 的另一种方法是获取所有页面 -> 循环它们 -> 创建一个 get_post_meta() if 语句。如果有值,则将当前页面添加到数组中。但正如您可以想象的那样,您必须加载所有页面,而您不应该这样做。

    希望对你有帮助,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 2013-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多