如何使用 post_type 中的自定义字段查询特定的自定义 post?

How to query specific custom post with custom fields in a post_type?

我是 wordpress 的新手,有点困惑如何在自定义 post 中获取 1 post。我只知道它在 post_type.

中回显所有内容的循环

我的目标是从 post_type 'product-category' 得到 1 post 而 meta_key 是 'product-category-and-type'

您可以在 wordpress 中尝试这个自定义查询:

$args = array(
            'post_type'     => 'product-category',
            'post_status'   => 'publish',
            "numberposts"   => 1,
            'meta_query' => array(
                array(
                    'key' => 'product-category-and-type',
                    'value' => 'meta_value'
                )
            )
        );

        $getPosts = new WP_Query($args);

只需将下面提到的代码复制并粘贴到您想要的位置,然后将 "your_meta_value" 替换为元键 "product-category-and-type" 的实际元值。

您将得到预期的结果:

<?php $args = array(
            'post_type'     => 'product-category',
            "numberposts"   => 1,
            'post_status'   => 'publish',
            'meta_query' => array(array('key' => 'product-category-and-type','value' => 'your_meta_value'))
            );

        $myposts = new WP_Query($args); 
        while($myposts->have_posts()) : $myposts->the_post();
        the_title();
         endwhile;?>
 $args = array(
    'post_type'  => 'product-category',
    'post_status' => 'publish',
    'posts_per_page' => '1',
    'tax_query' => array(
        array(
            'taxonomy' => 'product-category-and-type',
            'field'    => 'slug'
        ),
    ),
);

$result = new WP_Query($args);