PHP WordPress

How to create shortcode in wordpress

What is shorcode in wordpress?

Shortcode basically group of codes that perform an action while called via small code. For example: [myform] now when using this in theme or code editor it will display a form.

Lets see how to create this shortcode

To create shortcode add_shortcode action will be used.

in functions.php

<?php
/* * *********
 * ShortCode to Display Title
 * ShortCode : [Display-title]
 */

function display_text() {
    ob_start();
    the_title();
        return ob_get_clean();
} 
add_shortcode('Display-title', 'display_title');
?>

Explanation :

create a function and pass it to add_shortcode.

Basic Syntax is

<?php
add_shortcode('Shortcode-name', 'function_to_perform_working_of_shortcode');

ob_start() : It turn on output buffer.It returns true on success and false on failure

ob_get_clean : It deletes the current buffer.

How to write HTML in shortcode? What is shortcode template?

<?php
/* * *********
 * ShortCode to list all Parent Categories of Product Post Type
 * Post Type : products
 * Taxonomy : product-category
 * ShortCode : [product-parent-categories]
 */

function product_parent_categories_shortcode() {
    ob_start();
    ?>
    <div class="row">
        <div class="d-sm-flex flex-wrap w-75 mx-auto justify-content-center">
<?php // code to display product parent categories ?>
         </div>
    </div>
    <?php
    return ob_get_clean();
} 
add_shortcode('product-parent-categories', 'product_parent_categories_shortcode');

how to pass parameters to a shortcode?

create a shortcode to display list of posts and number of posts will be passed as parameter so shortcode will be [product-list NoPosts=6]

<?php
function product_list( $atts ) {
    ob_start();
   
    
                $args = array(
                    'post_type' => 'products',
                    'post_status' => 'publish',
                    'posts_per_page' => $atts['NoPosts'],
                    
                    ),
                );
                $my_query = new WP_Query($args);
    ?>
    <?php
     // code to display post list
    return ob_get_clean();
}
add_shortcode( 'product-list', 'product_list' );

References :

If this article helps you please do let me know in comments. your feedback will always be appreciated.

Leave a comment