Define a shortcode in function.php and call the shortcode in single.php, page.php or the article edit screen to display a list of articles easily.
Define shortcodes in function.php
Create a function that returns a list of articles.
Pass $args to WP_Query to retrieve the corresponding article list.
In this example, the eye-catching image of the retrieved article is displayed as the background image of the article tag.
This function generates the tag after the article is retrieved and returns.
function fetch_and_display_posts() {
$args = array(
'post_type' => 'post',
'posts_per_page' => 1000, // 取得する投稿数を設定
'orderby' => 'rand' // ランダムに並び替え
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$post_id = get_the_ID();
if( has_post_thumbnail() ) {
$eye_catch_image = get_the_post_thumbnail_url( get_the_ID(), 'medium' );
} else {
$eye_catch_image = get_template_directory_uri() . '/assets/img/ogp.png';
}
$output .= '<li class="box">';
$output .= "<article style='background-image: url({$eye_catch_image});' class='box_article'>";
$output .= '</article>';
$output .= '</li>';
}
wp_reset_postdata();
}
return $output;
}
Register a shortcode in the hook.
The first argument is the name used when calling the shortcode and the second argument is the name of the function to register in the hook.
add_shortcode('fetch_posts', 'fetch_and_display_posts');
Calling shortcodes
In single.php or page.php, call the shortcode, simply by using do_shortcode.
<ul class="random-container">
<?= do_shortcode('[fetch_posts]'); ?>
</ul>
Summary
The advantage is that the code is easier to read, as it can be summarised in a function with a shortcode.
Another useful feature is that it can be called from the article edit page.