最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - Related posts queries

programmeradmin0浏览0评论

Hey so I'm building a section that shows the related articles of a blog posts by doing a query with the post tags.

I thought this section was working but suddently it started showing 5 posts instead of 4.

I've read that get_posts uses 5 as the default number.

this is my query

$tags = wp_get_post_tags($post->ID);
        if ($tags) {
            $firstTag = $tags[0]->term_id;

            $argsRelated = array(

                'posts_per_page' => 4,
                'tag__in' => array($firstTag),
                'post__not_in' => array($post->ID),
                'ignore_sticky_posts'=>true,
                'nopaging' => true, 
            );
        }
        $relatedArticlesQuery = get_posts($argsRelated);



      <?php foreach ($relatedArticlesQuery  as $post) : setup_postdata( $post ); ?>
          <div class="related">
            <a href="<?php the_permalink();?>">
               <?php if(has_post_thumbnail( ))  : ?>
                   <span class="related__image display--block"style="background-image: url('<?php echo wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) ); ?>');">
                                </span> 
                      <?php else : ?>
                          <span class="related__image__none display--block">
                                </span>
                   <?php endif;?>
                        <span class="related__container display--block">
                          <p class="related__container__title">
                                      <?php echo get_the_date(); ?>
                           </p>
                            <h2 class="related__container__subtitle">
                                            <?php the_title(); ?>
                            </h2>
                          </span>
                         </a>
                     </div>
                <?php endforeach;?>

And this is my loop.

I also tried to do the loop with the wp_query function but it only returns 1 post, and it's the current post

Like this:

 $relatedArticlesQuery = new WP_Query($argsRelated);

And the loop like this

<?php $i = 1; while ($relatedArticles && $i < 4) : the_post(); );?>
        //cards 
<?php $i++; endwhile;?>


The final test i made was to use a while cicle using a while


<?php $i = 1; while ($relatedArticles && $i < 4) : setup_postdata( $relatedArticles[$i] );?>
        //cards 
<?php $i++; endwhile;?>

The stupid thing is that posts_per_page and numberposts don't work!!

Sorry for the long post

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论