[How to] Combine Multiple Shortcodes in WordPress
You can create shortcodes for any function in wordpress. It’s so easy to create one and also so functional. In this post i will show you how to use a shortcode in another shortcode.
Basically shortcodes are working in this way:
[shortcode {arguments}] -> shortcode_function({arguments}) -> return output
Let’s say you have a download_link shortcode from your download manager. Skeleton for this shortcode would be:
function download_link_shortcode($atts = ''){ // Extract shortcode attributes // Do stuff here and return link return $link; } add_shortcode('download_link', 'download_link_shortcode');
Let’s combine this shortcode with adsense widget shortcode. So we can easily output a download link with adsense below it.
Here is the skeleton for the shortcode.
>function download_with_adsense($atts = ''){ } add_shortcode('download_with_ads', 'download_with_adsense');
Now let’s fill in our shortcode function:
function download_with_adsense($atts = ''){ // Extract attributes here so we can use them as variables extract(shortcode_atts( array( 'id' => '' 'ad_type' => 'half-banner', 'ad_content' => 'image', 'ad_channel' => '12345678990' ), $atts)); $output = '<div class="wrap">'; // Now let's run our shortcodes and get output to combine // Get the download link $output .= do_shortcode('[download_link id="'.$id.'"]'); // Add adsense below the link $output .= do_shortcode('[adsense type="'.$ad_type.'" content="'.$ad_content.'" channel="'.$channel.'"]'); // Close wrapper div $output .= '</div>'; // Shortcodes never echo but return output. return $output; }
Now when ever we need a download link with adsense we can use this simple shortcode:
[download_with_ads id="3" ad_type="banner"]
Can you see how much time it saves?!
PHP + WordPress is amazing really 🙂
Deal Notice: We are using A2 hosting for all of our websites, and we are really happy with their service. So we wanted to share you this discount link for you to try it out. If you get a hosting using this link, you will also help us build better content for you: SSD Hosting - 300% Faster Than Standard Hard Drives