Вопрос

i need to display the latest 5 posts of each post type, something like:

Latest BMW Posts:

  • Post title BMW 1
  • Post title BMW 2

Latest Audi Posts:

  • Post title Audi 1
  • Post title Audi 2

And so on.

It seems that https://codex.wordpress.org/Function_Reference/wp_get_recent_posts does it. Something like:

<h2>Latest BMW Posts:</h2>
<ul>
<?php
    $args = array(
    'numberposts' => 5,
    'post_type' => 'bmw'
);
    $recent_posts = wp_get_recent_posts( $args );
    foreach( $recent_posts as $recent ){
        echo '<li><a href="' . get_permalink($recent["ID"]) . '">' .   $recent["post_title"].'</a> </li> ';
    }
    wp_reset_query();
?>
</ul>

<h2>Latest Audi Posts:</h2>
<ul>
<?php
    $args = array(
    'numberposts' => 5,
    'post_type' => 'audi'
);
    $recent_posts = wp_get_recent_posts( $args );
    foreach( $recent_posts as $recent ){
        echo '<li><a href="' . get_permalink($recent["ID"]) . '">' .   $recent["post_title"].'</a> </li> ';
    }
    wp_reset_query();
?>
</ul>

The problem is: when you have 10 or more types it can get overwhelming.

  1. Can the code be used with an array of post types and loop them to avoid repeating the same code for each type?
  2. Is this really a light task or would it kill MySQL? If so what's the most efficient way to get such output?
Это было полезно?

Решение

<?php $post_types = array(
    'bmw' => 'BMW',  // post type to use in query => post type to show in <h2>
    'audi' => 'Audi'

); 

foreach( $post_types as $post_type => $post_type_name ):
?>

    <h2>Latest <?php echo $post_type_name; ?> Posts:</h2>
    <ul>
    <?php
        $args = array(
        'numberposts' => 5,
        'post_type' => $post_type
    );
        $recent_posts = wp_get_recent_posts( $args );
        foreach( $recent_posts as $recent ){
            echo '<li><a href="' . get_permalink($recent["ID"]) . '">' .   $recent["post_title"].'</a> </li> ';
        }
        wp_reset_query();
    ?>
    </ul>
<?php endforeach; ?>

I think it's better to use wp_get_recent_posts is better than one single query, because of the filters that may be triggered, because of query cache, because the Db can be scaled into partitions for each post type and because there's no good single query to get all the info faster.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с wordpress.stackexchange
scroll top