WordPress does not allow us to add PHP code to pages, posts or any custom post types. However, we can create custom functions which are executed when a shortcode is encountered within the post text.
Simple shortcodes:-
Shortcode functions can be added to theme's functions.php file.
Here's a simple “Hello World” example:
add_shortcode('hello_world', 'my_shortcode_func');
function my_shortcode_func() {
return '<p>Hello World!</p>';
}
Enter [hello_world] in the required position in a page or post to output the result ( i.e. Hello World!).
Shortcodes with Parameters:-
The below shortcode function output image with custom width and height (i.e. you can specify width and height in shortcode)).
add_shortcode( 'dynamic_image', 'my_dynamic_image_func' );
function my_dynamic_image_func( $atts = '' ) {
$attributes = shortcode_atts( array(
'width' => 500,
'height' => 300,
), $atts );
return '<img src="https://via.placeholder.com/'. $attributes['width'] . 'x'. $attributes['height'] . '" />';
}
Enter [dynamic_image width="700" height="500"] shortcode somewhere within a page or post to output the image.
Comments
Post a Comment