How to use WordPress Shortcode Function

shortcode wordpress

All WordPress works are taken from Page Bulider. Whether we have to create a new page. But many times we have to do custom work within the theme according to the client.

For this, we cannot write custom code inside the page builder or editor. Because the PHP code is written in the PHP file itself. For some particular pages, we create a page template and write the custom code of the first work there.

But some work happens for which we have to use WordPress shortcode. Like we have to do some work with page builder and on the same page do some work with PHP code. For this, we use the WordPress shortcode.

Like we have to get some recent posts inside the page builder. But according to our design posts are not available inside the page builder. Then for this, we have to create a shortcode and call it inside the page builder

The shortcut to WordPress is given below. We write this shortcode inside the functions.php file. Whatever our HTML design. We write it inside shortcodes. In the same HTML, we write PHP code accordingly.

function function_name(){
ob_start();

?>
/* Start custom code here*/ Your all custom code here

<?php

echo 'This is a WordPress shortcode.';

?>

/* end custom code*/

<?php
$content =    ob_get_contents(); 
ob_get_clean();
return trim($content);
}
add_shortcode('shortcode_name' , 'function_name');

A shortcode is shown below. How do they do that. The shortcode given below has a function name latest_post. It has a shortcode name latestPost.

In this shortcode we have called the latest post of WordPress.

<?php

function latest_post(){
ob_start();

?>

/* Start custom code here*/

	<div class="row">
		<?php
		$args = array(
		'post_type' => 'post',
		'post_status' => 'publish',
		'posts_per_page' => 12,
		);
		$the_query = new WP_Query($args);
		while ($the_query->have_posts()) : $the_query->the_post();
		$image_id = get_post_thumbnail_id(); $image_url = etheme_get_resized_url($image_id,193,250,true);
		?> 
	
			<div class="col-md-6">
			<a href="<?php the_permalink(); ?>">
			<div class="basic-padding">
			<div class="image-hover">
			<img src="<?php echo $image_url;?>" alt="<?php the_title(); ?>" />
			
			<div class="overlay">
			<h2 style="color:#fff;"><?php the_title(); ?></h2>
			
			</div>
			</div>
			</div>
			</a>
			</div>
	
		<?php
		endwhile;
		wp_reset_query();
		?>
	
	</div>

/* end custom code*/

<?php
$content =    ob_get_contents(); 
ob_get_clean();
return trim($content);
}
add_shortcode('latestPost' , 'latest_post');

WordPress shortcode is used in the WordPress editor or page builder

shortcode name

shortcode with page builder

WordPress Shortcode use in PHP file

<?php echo do_shorcode('[latestPost]');?>

Leave a Reply

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