M
M
Mako422020-07-31 00:02:00
WordPress
Mako42, 2020-07-31 00:02:00

How to display the last 4 posts in wordpress?

There is a post output code:

<?php $wp_query = new WP_Query(array(
                                'posts_per_page' => 4
                            ));
                            if(have_posts()) : while (have_posts()) : the_post(); ?>
                                    <?php get_template_part('content', 'masonry'); ?>
                                <?php endwhile; endif; ?>

for some reason, it displays the last 8 posts, although posts_per_page is set to 4. If I define a category (heading) with the argument 'cat' => 322, then it starts displaying 4 each. I want it to display the last 4 posts from all categories (headings).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mako42, 2020-08-01
@Mako42

Solved the question in this way, adding to the argument with all the necessary categories, but it's more like a crutch

$args = [
    'cat' =>[529, 154, 525, 295, 160, 515, 523, 142, 521, 517, 527, 519],
    'posts_per_page' => 4,
    'order' => 'DESC',
    'orderby' => 'date',
    'post__not_in' => [get_the_ID()]
];
$wp_query = new WP_Query($args);
if($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
    <?php get_template_part('content', 'masonry'); ?>
<?php endwhile; endif; wp_reset_postdata(); ?>

A
Alexander Lopatin, 2020-07-31
@ClipClock08

<?php
$args = [
'posts_per_page' => 4,
'order' => DESC,
'orderby' => date,
'post__not_in' = [get_the_ID()]
]
$wp_query = new WP_Query($args);
if($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
<?php get_template_part('content', 'masonry'); ?>
<?php endwhile; endif; wp_reset_postdata(); ?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question