Shortcode with custom content attribute?

I am creating a shortcode for a client site that should display an image and a saying (mainly at the bottom of the page, but basically wherever the client wants to insert said image/saying). The image would remain the same, and there will be a “standard saying”, but the client would like the potential to change the saying on a per-page basis.

I have the following working code which works great when using the [call_to_action] shortcode:

Read More
<?php 
function shortcode_call_to_action() { 
$stylesheetdir = get_bloginfo('stylesheet_directory');
return '<div id="call_to_action"> <img src="' . $stylesheetdir . '/images/call_to_action.jpg" /> 
        <p>Lorem ipsum dolor sit amet, jus ludus dignissim delenit incassum adipiscing, letalis ymo loquor populus sed saepius. Quod regula vulputate eum nulla, feugait foras ex ideo. </p>' ;
}
add_shortcode('call_to_action', 'shortcode_call_to_action');    
?>

What I’d like to do, somehow, is add an attribute in there, somewhere, so that the client can change/overwrite the call_to_action text by changing it right in the shortcode:

[call_to_action]This would be the new overwritten text that would show up if inserted here.[/call_to_action]

I would also like it to respect any html (paragraph and/or break) tags that might be used. Willing to re-write my previous function if necessary. I’m a php noob so I can’t seem to figure this one out. Any help is greatly appreciated. Thanks SE!

Related posts

Leave a Reply

1 comment

  1. The second parameter of your shortcode function is the content. So rewrite the function:

    function shortcode_call_to_action( $attributes = NULL, $content = '' ) 
    { 
        $stylesheetdir = get_bloginfo('stylesheet_directory');
    
        if ( '' === $content )
        {   // use a default text if there is no content
            $content = 'default text';
        }
    
        return "<div id='call_to_action'> <img src='$stylesheetdir/images/call_to_action.jpg' alt='' /> 
            <p>$content</p>";
    }
    

    If the user writes …

    [call_to_action]Custom text[/call_to_action]
    

    … the parameter $content in your function will be set to that text.

    For more details see the Shortcode API.