wordpress shortcodes

Create a new php file and include it in the main functions.php file. We will write shortcode detail in that file.

function headingStyle(){
	return '<h1>hello</h1>';
}

add_shortcode("heading", "headingStyle");

In the above code, we defined that whenever we will use the [heading] inside any post/page that shortcode will be replaced by hello inside <h1> tag.

Using shortcode [short][/short]::

function headingStyle($atts, $content){
	return '<h1>'.$content.'</h1>';
}

add_shortcode("heading", "headingStyle");

Now we can use [heading][/heading]. The text which will be place inside the shortcode, will get heading1 style

Receiving attribute via shortcodes

function headingStyle($atts, $content){
	
	$heading = shortcode_atts(array(
		'color' => 'red'
	), $atts);
	 
	return '<h1 style="color:'.$heading['color'].'">'.$content.'</h1>';
}

add_shortcode("heading", "headingStyle");

Using a large block in a shortcode…..

function zboom_block_shortcode(){
	ob_start(); 
	?>
	
	All HTML code goes here and all will be returned....
	
	<?php
	$block = ob_get_clean();
	return $block;
}

add_shortcode("block", "zboom_block_shortcode");

Full fledged shortcode which uses a chunk of HTML code block inside the function and returns it..

function blockShortcode($atts, $content){
	ob_start();
	
	$attrib = shortcode_atts(array(
		"number" => 3
	), $atts);
	
	?>

	<?php
            $infoBlocks = new WP_Query(array(
                'post_type' => 'infoBlocks',
                'posts_per_page' => $attrib["number"]
            ));
            ?>

            <?php while ($infoBlocks->have_posts()): $infoBlocks->the_post(); ?>

                <div class="col-1-3">
                    <div class="wrap-col box">
                        <h2><?php the_title(); ?></h2>
                        <p><?php echo returnWords(get_the_content(), 10); ?></p>
                        <div class="more"><a href="<?php the_permalink(); ?>">[...]</a></div>
                    </div>
                </div>

            <?php endwhile; ?>

	<?php
	$xyz = ob_get_clean();
	return $xyz;
}

add_shortcode("block", "blockShortcode");

Enabling shortcodes in widgets:

Normally shortcode wont work in widgets. To enable the functionality, we have to add a filter in the after_setup_theme hook as below

function zboom_default_functions(){
    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('custom-background');
    
    add_filter("widget_text", "do_shortcode");
}
add_action('after_setup_theme', 'zboom_default_functions');

 

 

  • It does not works in title.
  • If you are showing counted words in the blog page, the shortcode wont convert.

Leave a Reply

Your email address will not be published. Required fields are marked *