I have created a new Block for the WordPress Editor, and I am trying to get a simple WP_Query to work, but so far, the $args
in the query are mostly ignored, apart from the post_type
setting. For example, I want to set posts_per_page
to 3, but this is ignored. Why is this?
<?php
wp_reset_postdata();
wp_reset_query();
$latest_news_args = [
'post_type' => 'post',
'posts_per_page' => 2,
'post_status' => 'publish',
'nopaging' => true,
'ignore_sticky_posts' => true
];
$latest_news_query = new WP_Query($latest_news_args);
if ($latest_news_query->have_posts()) : while ($latest_news_query->have_posts()) : $latest_news_query->the_post();
$post_id = get_the_ID();
$post_title = get_the_title();
$post_url = get_the_permalink();
$post_excerpt = get_the_excerpt();
$post_image = get_the_post_thumbnail_url();
$post_image_id = get_post_thumbnail_id( $post->ID );
$post_image_alt_meta = get_post_meta ( $post_image_id, '_wp_attachment_image_alt', true );
$post_image_alt = $post_image_alt_meta ? esc_html($post_image_alt_meta) : $post_title; // If no alt text specified, fall back to post title
?>
<div class="latest-news-block__post">
<?php if($post_image): ?>
<img class="latest-news-block__post-image" src="<?php echo $post_image; ?>" alt="<?php echo $post_image_alt; ?>">
<?php endif; ?>
<h3 class="latest-news-block__post-title">
<a href="<?php echo $post_url; ?>"><?php echo $post_title; ?></a>
</h3>
<div class="latest-news-block__post-excerpt">
<p><?php echo $post_excerpt; ?></p>
<a href="<?php echo $post_url; ?>" class="latest-news-block__post-more more-link"><?php _e('Read more','site'); ?></a>
</div>
</div>
<?php endwhile; endif; wp_reset_postdata(); wp_reset_query(); ?>