doushou3814 2016-04-07 15:41 采纳率: 100%
浏览 51

如何获取当前自定义帖子的子帖子并按自定义字段编号进行排序?

I have custom post type 'cars' and its child post type is 'carvariants'.

What I want to do is get child posts (carvariants) of current post (cars). I tried this code:

    <div>
    <?php 
    $parent_id = 1064;
    $the_query = new WP_Query(array(
'post_parent' => $parent_id,
        'post_type'         => 'carvariants',
        'posts_per_page'    => 1,
        'meta_key'          => 'wpcf-minimum-price',
        'orderby'           => 'meta_value_num',
        'order'             => 'ASC'
    ));

    ?>
    <?php if( $the_query->have_posts() ): ?>
        <ul>
        <?php while( $the_query->have_posts() ) : $the_query->the_post(); 
                $compprd = get_the_ID(); ?>

  <?php the_title(); ?>
     <?php
         endwhile; ?>
        </ul>
    <?php endif; ?>
    <?php wp_reset_query();  ?>
    </div>

I want to display child posts of Cars order by custom field wpcf-minimum-price but 'post_parent' is not working. This code is showing blank output. Whats wrong in this?

  • 写回答

1条回答 默认 最新

  • dongmozhui3805 2016-04-08 12:08
    关注

    I didn't try this. But I hope this will work.

    If it will not work, leave me a comment, and I will try to make it work.

    Also, if there are better solutions, I will be glad to see the code from professionals:

    <div>
        <?php 
        $parent_id = 1064;
        $args = array( 'child_of' => $parent_id );
    
        $children_pages = get_pages( $args );
    
        if ( count( $children_pages ) != 0 ) :
            foreach ( $children_pages as $children_page ) :
                if ( $children_page->have_posts() ) :
                        $args_for_posts = array( 'posts_per_page' => 1,
                            'post_type' => 'carvariants',
                            'orderby' => 'meta_value_num',
                            'order' => 'ASC',
                            'post_parent' => $children_page );
                        $postlist = get_posts( $args_for_posts );
                        foreach ( $postlist as $post) :
                            setup_postdata( $post ); ?>
                            <ul>
                                <?php
                                the_post();
                                ?>
                            </ul>    
                        <?php
                        endforeach;
                        wp_reset_postdata();
                endif;
            endforeach;
        else : ?>
            <p>No content to show.</p>
        <?php 
        endif; ?>
    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计