How to create a shortcode with html and php code

For creating a shortcode, you need a shortcode action and a function which will execute when the shortcode is called. So here is an example of how you can do it.

I am adding a simple shortcode which will run on a single post page. So we have to get a post variable which is defined globally in WordPress. You can simply call it via

global $post;

If you want to print some post meta like I want to print post second image and I created second_image as a meta key from ACF.

So I can simply print it via the following code.

add_shortcode('print_second_image','func_print_second_image');
function func_print_second_image(){
global $post;
return get_post_meta($post->ID,'second_image',true);
}

Note*
The second parameter of add_shortcode will be the function name which will be called when you call shortcode. You can define shortcode like anything you want but for function, you have to remember following things

– The name of the function cannot start with a number.
– A PHP function cannot be overloaded or redefined.
– PHP functions are case-insensitive.
– Any variable declared and defined within a function is restricted within the function only – Unless, accompanied by a “global” keyword.

Want us to do this for you?