doujia1939 2014-03-29 21:41
浏览 76
已采纳

查询由post_object自定义字段过滤的帖子

I am trying to query any post which has a certain post_object selected as its "parent". The parent value will have to match the ID of the current post. I have been able to replicate this functionality by querying all posts of this post type and then comparing the values within the loop, like so:

<?php
    $wp_query = new WP_Query();
    $wp_query->query(  array (
        'post_type' => 'my_post_type',
        'meta_key'=>'post_object_field'
)); 

if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

    <?php 
    $parent = get_field('post_object_field'); 
    $parentId = $parent->ID; ?>

    <?php if ($postId == $parentId): ?>

        // content 

    <?php endif; ?>
<?php endwhile; endif; ?>

I'm wonder if there is a way to check for this value inside the query, and if so, if it's any faster or more correct.

  • 写回答

3条回答 默认 最新

  • duanhangjian8149 2014-03-29 23:27
    关注

    To get all the posts/pages that are children of a given post/page, you can use the parameter post_parent, using the ID of the parent post.

    For example, if you have a post

    $wp_query->query(  array (
        'post_type'    => $children_post_type
        'post_parent'  => $postId
    )); 
    

    And of course, yes, performing a query will be much more efficient than performing a query + getting a field value + creating a variable + looping the results making a comparison...


    EDIT: According to your comments, it seems that you're actually trying to get all those posts that have a given value in a custom field of type Post Object. This field contains a number, which is the ID of the post it relates to, so you just need to add a parameter meta_value_num in your query:

    $wp_query->query(  array (
        'post_type'      => 'my_post_type',
        'meta_key'       => 'post_object_field'
        'meta_value_num' => $postId
    ));
    

    This will retrieve all the posts that have a custom field called post_object_field with a value $postId.


    EDIT: Try this:

    $args = array(
    'post_type'  => 'my_post_type',
    'meta_query' => array(
        array(
            'key'     => 'post_object_field',
            'value'   => $postId,
            'compare' => '='
        )
    )
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 slam rangenet++配置
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊