Create shortcode in wordpress functions php

Created at 02-Aug-2023 , By samar

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.

  1. Access the functions.php file located at yourproejct\wp-content\themes\generatepress-child your current active theme.
  2. 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');
  1. 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.

Buy Me A Coffee

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.