【问题标题】:Order WP_Query by meta and post date按元和发布日期订购 WP_Query
【发布时间】:2013-04-30 05:57:59
【问题描述】:

我目前正在开发一个小型博客,该博客有一个显示所有“特殊项目”的侧边栏。

“特殊项目”只是一个类别,侧边栏一次只会显示 4 个按发布日期过滤的帖子,但我也有一个自定义元框以允许用户展示帖子。 这些精选帖子应显示在特殊项目的顶部。

现在我的查询是这样的:

new WP_Query("showposts=" . $instance['num'] . "&cat=" . $instance["cat"] . "&order=ASC&order_by=date")

我可以像这样获得特色元数据:

 $featured = get_post_meta($single_cat_post->ID, 'soy_featured_post', true);

但是我怎样才能将它集成到 WP_Query 中呢?

【问题讨论】:

    标签: wordpress blogs meta


    【解决方案1】:

    首先,在使用 WP_Query 时,“showposts”已被“posts_per_page”取代。我已经在你的代码中更正了。此外,在循环中,您应该能够使用 $post->ID 而不是 $single_cat_post->ID。

    我会使用两个循环。设置您的参数,然后在第一个循环中包含一个检查元值的条件,重置查询,然后执行另一个循环并包含一个检查元值的条件,如果存在则不输出任何内容。

    在第一个查询中,我添加了一个检查以查看第一个循环返回了多少帖子。然后使用该值(减去 4)我计算了一个用于第二个循环中的 posts_per_page 的变量。然后我添加了一个条件,仅当结果大于 0 时才运行循环。

    这是未经测试的,但它应该可以工作,或者至少让你走上正确的道路!

    <?php 
    $args = array(
        'posts_per_page' => 4,
        'meta_key'  => 'soy_featured_post',
        'cat' => $instance["cat"],
        'orderby' => 'date',
        'order' => 'ASC'
    );
    
    $special_post_query = new WP_Query( $args );
    $special_posts_found = $special_post_query->found_posts;
    
    if ($special_post_query->have_posts()) :
        while( $special_post_query->have_posts() ) : $special_post_query->the_post(); 
    
        // POST WITH META VALUE OUTPUT
        the_title();
    
        endwhile;
    endif;
    
    wp_reset_query();
    
    $second_loop_posts_per_page = 4 - $special_posts_found;
    
    if ($second_loop_posts_per_page > 0) {
        $args = array(
            'posts_per_page' => $second_loop_posts_per_page,
            'cat' => $instance["cat"],
            'orderby' => 'date',
            'order' => 'ASC'
        );
    
        if ($special_post_query->have_posts() ) :
            while( $special_post_query->have_posts() ) : $special_post_query->the_post(); 
    
            // Condition to test for NO meta value
            if (get_post_meta($post->ID, 'soy_featured_post', true) == null) {
                // CODE
                the_title();
            } else {
                // Don't print anything because the meta value exists
            }
    
            endwhile;
        endif;
    
        wp_reset_query();
    } ?>
    

    【讨论】:

      猜你喜欢
      • 2011-10-20
      • 2020-06-21
      • 2023-01-14
      • 1970-01-01
      • 1970-01-01
      • 2015-09-07
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      相关资源
      最近更新 更多