Created
December 27, 2024 12:02
-
-
Save SitesByYogi/36bceb62d9edb5d3fd907cd2b7791c1f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Add this code to your theme's functions.php file or use the Code Snippets plugin. | |
/** | |
* Recent Blog Posts Shortcode with Title | |
*/ | |
function custom_recent_blog_posts_shortcode($atts) { | |
// Extract attributes | |
$atts = shortcode_atts(array( | |
'number' => 8, // Default number of posts to display | |
'title' => 'Read Our Blogs', // Default title | |
), $atts, 'recent_blogs'); | |
// Query for recent blog posts | |
$recent_posts = new WP_Query(array( | |
'post_type' => 'post', | |
'posts_per_page' => intval($atts['number']), | |
'post_status' => 'publish', | |
)); | |
// Build the output | |
ob_start(); | |
echo '<div class="recent-blog-posts-wrapper">'; | |
// Display the title | |
if (!empty($atts['title'])) { | |
echo '<h2 class="recent-blog-title">' . esc_html($atts['title']) . '</h2>'; | |
} | |
// Display the list of blog posts | |
if ($recent_posts->have_posts()) { | |
echo '<ul class="recent-blog-posts">'; | |
while ($recent_posts->have_posts()) { | |
$recent_posts->the_post(); | |
?> | |
<li> | |
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> | |
</li> | |
<?php | |
} | |
echo '</ul>'; | |
} else { | |
echo '<p>No recent posts found.</p>'; | |
} | |
echo '</div>'; | |
wp_reset_postdata(); | |
return ob_get_clean(); | |
} | |
add_shortcode('recent_blogs', 'custom_recent_blog_posts_shortcode'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment