avatar
create Shortcode with Parameters in Wordpress WordPress

» First and foremost, WordPress Shortcodes are tags like `[gallery]` or `[video]` that let you easily add dynamic content or execute custom functions in posts, pages, or widgets.

For example:

[youtube url="https://www.youtube.com/watch?v=YOUR_VIDEO_ID"]

» Leverage the `add_shortcode()` function, which is WordPress function used to register custom shortcodes.

Hence, we will separate it into two steps as below:

// Initialize function for the shortcode
function create_shortcode() {
  echo "Hello World!";
}
// Create a shortcode named [test_shortcode] and execute the code from the create_shortcode function
add_shortcode( 'test_shortcode', 'create_shortcode' );

» In WordPress, there are existing terms and functions used to add, modify, or extend the functionality of site.

  • `add_theme_support()`: Adds support for various WordPress features like post thumbnails, custom logos, etc.
  • `register_nav_menus()`: Registers custom navigation menus.
  • `add_image_size()`: Adds custom image sizes.

You can refer to the link here. Now, Now, let assume that we will write a shortcode using `WP_Query` to fetch random set of posts with parameter for the number of posts in WordPress.

» functions.php

function create_shortcode_randompost($atts) {
    $atts = shortcode_atts(
        array(
            'n' => 10, 
        ),
        $atts,
        'random_post'
    );

    $n = intval($atts['n']);

    $random_query = new WP_Query(array(
        'posts_per_page' => $n,
        'orderby' => 'rand'
    ));

    ob_start();

    if ($random_query->have_posts()) :
        echo "<ol>"; 
        while ($random_query->have_posts()) : $random_query->the_post();
            echo '<li><a href="' . get_permalink() . '"><h5>' . get_the_title() . '</h5></a></li>';
        endwhile;
        echo "</ol>";
    endif;

    wp_reset_postdata();
    $list_post = ob_get_contents();
    ob_end_clean();
    return $list_post;
}

add_shortcode('random_post', 'create_shortcode_randompost');

» Use the shortcode `[random_post n="5"]` to display 5 random posts. Adjust n to change the number of posts, e.g., in Elementor Builder.

In some cases, to embed posts in card view and set the number of posts via GUI, modify the HTML structure for card layout. Follow the link here.

24
create custom Shortcodes in WordPress
You need to login to do this manipulation!