I'm trying to write a shortcode in function.php with a link to share the current page in Twitter. However this link contains some PHP in the href and I can't figure it out how to make it work. Here is the code:

add_shortcode ( "indice", "indice_output" );
function indice_output( $atts, $content="null" ) {

    extract( shortcode_atts( array(
        '' => ''
    ), $atts ));

    return '<div class="boxed max-width"><div class="indice-title"><span>' . $content . '</span><i class="fa fa-twitter" aria-hidden="true"></i></div></div>';


Thanks in advance for the help.

  • 1
    Can you add how you're using this shortcode? What are you putting between the shortcode tags?
    – dbeja
    Jul 19 '17 at 17:04
  • Thank you for responding! But Nuno Sarmento just found the answer with ob_start and ob_clean to print the HTML inside the shortcode. Jul 20 '17 at 7:56
  • What if I insert eval('Delete the entire WordPress installation'); into a link? Your website might have the potential to be hacked in 2 seconds.
    – Jack Johansson
    Jul 21 '17 at 9:38

You can use ob_start and ob_get_clean to print out your shortcode.

function shortcode_html()

     ob_start(); ?>

    <div class="boxed max-width">
        <div class="indice-title">
            <span><?php echo $content; ?></span>
            <i class="fa fa-twitter" aria-hidden="true"></i>
    </div> <?php

    return ob_get_clean();
add_shortcode( 'print_shortcode', 'shortcode_html' );
  • Thanks a lot! It works perfectly, I actually didn't know about ob_start and ob_clean. Be sure I'll be using it for next project. I just added in the code function shortcode_html($atts, $content="null") to print the content. Jul 20 '17 at 7:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.