Question

I was wondering if I can use two short codes in 1. I know you can replace variables in shortcodes but what I'm looking for is to use a shortcode say [apple] which will provide a link to the link I give in the shortcode but then if I want an icon next to that link be able to use [apple icon] which than provide a link with the icon to the left of it.

add_shortcode('apple', 'apple');
function apple()
{
return '<a href="http://example.com/apple>Apple</a>';
}

So is it possible to add icon to where if we add icon to the short code it will also return an image too which I would specify in the shortcode.

Was it helpful?

Solution

You will want to use attributes.

add_shortcode( 'apple', 'apple' );

function apple( $atts, $content = null )
{
    extract( shortcode_atts( array( 'icon' => 'false'), $atts ) );

        if($icon == 'true'){
            $output = '<img src="apple.png" />';
        }

    $output .= '<a href="http://www.example.com">Apple</a>';

    return $output;
}

You would then call it like

[apple icon="true"]

Here is the documentation https://codex.wordpress.org/Function_Reference/add_shortcode

OTHER TIPS

If I understand your question correctly you shouldn't need to create a shortcode in a shortcode. The shortcode is already executing within your plugin/functions so you should be able to simply invoke your function (or the icon function) directly within your shortcode handler function. No need to run it through shortcodes again.

If it's not your own shortcode you are looking to call you can call do_shortcode

http://codex.wordpress.org/Function_Reference/do_shortcode

To do what you want, it's not necessary to have two shortcodes, just make your shortcode accept arguments:

add_shortcode('apple', 'apple');

function apple($args) {
    $default = array('icon' => '');
    $args = wp_parse_args($args, $default);

    $content = '';
    if ($args['icon']) {
        $content.= '<img src="icon.png">';
    }

    $content.= '<a href="http://example.com/apple>Apple</a>';

    return $content;
}

To use this, you would then enter your shortcode as follows:

[apple icon="yes"]

If it's simply a "yes/no" for the icon.

Or, you could make it so it loads the icon dynamically based on what you set icon equal to, which would require some modifications to the function:

function apple($args) {
    $default = array('icon' => '');
    $args = wp_parse_args($args, $default);

    $content = '';
    if ($args['icon']) {
        $content.= '<img src="' . $args['icon'] . '">';
    }

    $content.= '<a href="http://example.com/apple>Apple</a>';

    return $content;
}

And your shortcode would then look like so:

[apple icon="my_icon.png"]

(Note, you'd probably need to pass in a fully qualified domain name, like so: [apple icon="http://example.com/images/my_icon.png"])

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top