Button Shortcode for WordPress

Posted on: June 17th, 2022
By: Tadeo Martinez

Add the below code to your functions.php

function btn_shortcode( $atts, $content = null ) {

	$a = shortcode_atts( array(
	
	'class' => '',
	
	'href' => '',
	
	'style' => '',
	
	'target' => '',

	'id' => '',
	
	'aria-label' => ''
	
	), $atts );

	$id = esc_attr($a['id']);

	// Check if the ID contains the word "modal"
	if (strpos($id, 'modal') !== false) {
		return '<span class="btn-main open-modal ' . esc_attr($a['class']) . '" aria-label="' . esc_attr($a['aria-label']) . '" style="' . esc_attr($a['style']) . '" target="' . esc_attr($a['target']) . '" id="' . esc_attr($a['id']) . '">' . $content . '</span>';
	} else {
		return '<a class="btn-main ' . esc_attr($a['class']) . '" href="' . esc_attr($a['href']) . '" style="' . esc_attr($a['style']) . '" target="' . esc_attr($a['target']) . '" id="' . esc_attr($a['id']) . '">' . $content . '</a>';
	}
	
	// [button href="" id="" class="" style=""]Learn More[/button]
	
	}
	
add_shortcode( 'button', 'btn_shortcode' );

This dynamic shortcode allows you to add a button either that has a regular link or if it’s for a popup.

Below is the shortcode you would use in the Gutenberg or text editor area.

[button href="#" style="font-weight:bold; margin-top:50px; background-color: #999" target="_blank"]Learn More[/button]

Have any questions or comments? Write them below!


Leave a Reply

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