In this article, we will show you how to add the shortcode in WordPress. We will also show you how to create a shortcode in WordPress. Shortcodes is an easy way to add dynamic content into your WordPress posts, pages and widgets without adding any code directly.

If you want to add some custom code inside your posts or pages to display related posts, latest posts, contact forms, galleries, etc.. then use shortcode it allows you to add custom code inside the function and then register that function using add_shortcode() function.

Syntax:

add_shortcode( $tag , $func );

Explanation:

$tag: (string) (required) Shortcode name

$func: (callable) (required) Hook to run when the shortcode is found

ShortCode is displayed inside square brackets like this:

[my_shortcode]

To Create Shortcode Open /wp-content/themes/theme_name/functions.php file and place the following code.

<?php
function thecodehubs_shortcode() {
  ob_start();	
  $args = array( 'posts_per_page' => '-1', 'post_type' => 'post' );
  $the_query = new WP_Query( $args );
  if( $the_query->have_posts() ) : 
     while( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <p><?php _e( "Title:", "twentyseventeen-child" ) .the_title(); ?></p>
        <?php $terms = get_terms( array( 'taxonomy' => 'Author', 'orderby' => 'name' ) );
            foreach ( $terms as $term ) {
              echo  "Author: ".$term->name;
            } ?>
        <p><?php the_content(); ?></p>
    <?php endwhile; 
    wp_reset_postdata();
  endif;
  return ob_get_clean();
} 
add_shortcode( 'Postcontent', 'thecodehubs_shortcode' );
?>

Here are two methods to add the shortcode:
Method 1: Add shortcode to your post or page in WordPress please look at the below screenshot.

Method 2: Add ShortCode in Theme File

To use a shortcode at any WordPress theme template by using do_shortcode() function.

syntax:

do_shortcode( string $content, bool $ignore_html = false )

Parameters:

$content: (Required) Content to search for shortcodes.

$ignore_html: (Optional) When true, shortcodes inside HTML elements will be skipped.

Open /wp-content/themes/theme_name/template_name.php and put the below code.

<?php echo do_shortcode('[Postcontent]'); ?>

Now WordPress displays its output in your theme template.

Footer Logo

Subscribe

Select Categories