dongxie548548 2019-08-09 12:08
浏览 46

使用带有模板部分的index.php从wordpress中排除重复的帖子

I'm trying to avoid duplicates posts in one file - index.php where i do collection of the loops for categories. But no result. Please - help...

<div class="container-fluid newgray">
    <div class="container asia travel-news proppad">
        <?php get_template_part( 'inc/slider-news' );?>     
    </div>
</div>
<div class="container-fluid best">
    <div class="container travel-news proppad">
        <?php get_template_part( 'inc/best' );?>
    </div>
</div>
<div class="container-fluid newback over">
    <div class="container last travel-news proppad">
        <?php get_template_part( 'inc/latest' );?>      
    </div>
</div>

Trying use this code:

<?php
$do_not_duplicate = array(); // set befor loop variable as array

// 1. Loop
query_posts('ca=1,2,3&showposts=5');
while ( have_posts() ) : the_post();
    $do_not_duplicate[] = $post->ID; // remember ID's in loop
    // display post ...
    the_title();
endwhile;
?>

<?php
// 2. Loop
query_posts( 'cat=4,5,6&showposts=15' );
while (have_posts()) : the_post();
    if ( !in_array( $post->ID, $do_not_duplicate ) ) { // check IDs         
// display posts ...
        the_title();
    }
endwhile;
?>

But it works only when all loops in one php file…

  • 写回答

1条回答 默认 最新

  • doufei2328 2019-08-09 14:23
    关注

    This is How I wold do, don't waste your time repeating same code, it will be a hell if you need change something.

    function post_by_cat_ecluding($cats, $per_page, $exclude =  array()) {
        $html = '';
        $args = array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'category__in' => $cats,
            'posts_per_page' => $per_page,
            'post__not_in' => $exclude,
            'offset' => 0
        );
        $loop = new WP_Query($args);
    
        foreach ($loop->posts as $p) {
            $exclude[] = $p->ID;
            $html .= '<article><h2>'.$p->post_title.'</h2></article>';
        }
    
        return array('html' => $html, 'exclude' => $exclude);
    }
    
    $first_block = post_by_cat_ecluding(array(1,2), 5);
    echo $first_block['html'];
    
    $second_block = post_by_cat_ecluding(array(4,5), 15, $first_block['exclude']);
    echo $second_block['html'];
    
    评论

报告相同问题?

悬赏问题

  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题