How to Create Image & Button Shortcode in WordPress

Looking for code snippets to create shortcodes for image and button in WordPress?.

Here are the code snippets, Just add these snippets in your theme’s functions.php file and you are good to go.

Create Image Shortcode

To create image shortcode, all you need to do is just add this code into the functions.php file.

//==============================================================
// Dive in WP - Shortcode For Image
//==============================================================

function diwp_image_shortcode($attr){

	$args = shortcode_atts(

			array(
				'src'   => '#',
				'title' => '',
				'alt'   => '',
				'class' => ''	
					  
		     ), $attr);
   
   $image = '<img src="'.$args['src'].'" title="'.$args['title'].'" alt="'.$args['alt'].'" class="'.$args['class'].'" />';

   return $image;

}

add_shortcode('diwp-image', 'diwp_image_shortcode');

Then use this [diwp-image src=”link_to_your_image”] shortcode in to create an image. [diwp-image] shortcode accepts some parameters as given below. Where src is required to display image and others are optional.

  • src = this is required to display an image.
  • title = you can set the title for the image.
  • alt = you can set alt text for image.
  • class = you can set class for image.

Create Button Shortcode

To create button shortcodes, all you need to do is just add this code into the functions.php file.


//==============================================================
// Dive in WP - Shortcode For Button
//==============================================================

function diwp_button_shortcode($attr){

	$args = shortcode_atts(

				array(
						'link'   => '#',
						'bgcolor' => '#1a73e8',
						'textcolor' => '#FFF',
						'text' => 'Button',
					  
					  ), $attr);

	$button = '<a href="'.$args['link'].'" style="background:'.$args['bgcolor'].'; color:'.$args['textcolor'].'; padding: 8px 20px; display: inline-block; border-radius: 4px; font-size: inherit;margin: 15px 0px;">'.$args['text'].'</a>';

	return $button;
}

add_shortcode('diwp-button', 'diwp_button_shortcode');

Then use this [diwp-button link=”link_to_page”] shortcode in to create a button. [diwp-button] shortcode accepts some parameters as given below.

  • link = link or URL on which it should go when clicking on the button.
  • text = to set the text of the button.
  • bgcolor = to set the background color of the button.
  • textcolor = to set the font color of the button.

I hope these snippets will help you to create images and buttons so easily by using shortcodes and their attributes.

Share & Help Us to Grow..!

Advertisement

Related Posts

Leave a Reply

Your email address will not be published.

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top