Create shortcode in wordpress functions php
In WordPress, you can create a custom shortcode in the functions.php file of your theme or child theme. Shortcodes allow you to easily insert custom functionality or content into your posts, pages, or widgets using a simple and intuitive syntax like [latest-posts].
Here's how you can create a custom shortcode in the functions.php file and use it in your posts, pages, or widgets.
- Access the functions.php file located at yourproejct\wp-content\themes\generatepress-child your current active theme.
- Create shortcode functionality in it (functions.php) using below code. Simply copy and paste code at the end of functions.php file and save the file.
function display_latest_posts_shortcode($atts) {
// Extract shortcode attributes
$atts = shortcode_atts(array(
'num_posts' => 5, // Default value for the number of posts to display
), $atts);
// Query the latest posts
$latest_posts_args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => intval($atts['num_posts']),
);
$latest_posts = new WP_Query($latest_posts_args);
// Prepare the output
$output = '<ul>';
if ($latest_posts->have_posts()) {
while ($latest_posts->have_posts()) {
$latest_posts->the_post();
$output .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
}
} else {
$output .= '<li>No posts found.</li>';
}
$output .= '</ul>';
// Reset post data
wp_reset_postdata();
return $output;
}
add_shortcode('latest_posts', 'display_latest_posts_shortcode');
- To add a shortcode, create a new page/post or edit the existing page/post. You have to simplye click on add block button (button with plus icon) in your editor and search for shortcode element and paste the below code in it.
[latest_posts]
You can now use the [latest_posts] shortcode in your WordPress content (posts, pages, or widgets) to display the latest posts.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
Don't forget to share this article! Help us spread the word by clicking the share button below.
We appreciate your support and are committed to providing you valuable and informative content.
We are thankful for your never ending support.
Random Code Snippet Queries: Wordpress
- Replace Live Site Url with Local Site URL in wordpress database
- Function to get the post id in while (have_posts()) : the_post();
- Create a accordion plugin in wordpress
- Remove every class and ID from the wp_nav_menu
- Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 2348617 bytes) in /home/xxx/public_html/wp-includes/plugin.php on line xxx
- Show template file name in wordpress
- How to display author avatar in Wordpress 5
- Remove class from body tag in wordpress
- Custom post type in wordpress
- How to use shop in product category and product permalink in woocommerce
- Add new class to body tag in wordpress
- How to hide PHP Warnings and Notices in WordPress?