Custom function to display 30 random published posts
-
Hello,
I need a custom function to display 30 random published posts in a post (a sort of random sitemap but for only 30 posts).
I’ve succeeded to code that by changing a small piece of code found on the internet, but as this code was made to create a chronological sitemap originally, I think the final result is much bigger than what I actually need. This is my code, it’s working fine, but how can make it shorter and more efficient from there without breaking it?
function sitemap_f( $atts ) { global $month, $wpdb, $wp_version; // a mysql query to get the list of distinct years and months that posts have been created $sql = 'SELECT DISTINCT YEAR(post_date) AS year, MONTH(post_date) AS month, count(ID) as posts FROM ' . $wpdb->posts . ' WHERE post_status="publish" GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY RAND()'; // use get_results to do a query directly on the database $archiveSummary = $wpdb->get_results($sql); $posts_affiches=0; $casse=0; $nombre_posts = 500; // if there are any posts if ($archiveSummary) { // loop through the posts foreach ($archiveSummary as $date) { // reset the query variable unset ($bmWp); // create a new query variable for the current month and year combination $bmWp = new WP_Query('year=' . $date->year . '&monthnum=' . zeroise($date->month, 2) . '&posts_per_page=-1'); // if there are any posts for that month display them if ($bmWp->have_posts()) { // display the archives heading $url = get_month_link($date->year, $date->month); $text = $month[zeroise($date->month, 2)] . ' ' . $date->year; echo get_archives_link($url, $text, '', '<h3>', '</h3>'); echo '<ul class="postspermonth">'; // display an unordered list of posts for the current month while ($bmWp->have_posts()) { $bmWp->the_post(); echo '<li><a href="' . get_permalink($bmWp->post) . '" title="' . wp_specialchars($text, 1) . '">' . wptexturize($bmWp->post->post_title) . '</a></li>'; $posts_affiches += 1; if ($posts_affiches == $nombre_posts) { $casse = 1; break; } } if ($casse == 1) { break; } echo '</ul>'; } } } } add_shortcode( 'sitemap', 'sitemap_f' );
Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
- The topic ‘Custom function to display 30 random published posts’ is closed to new replies.