Adding php directly into widget shortcode

To be honest, if you see yourself in the need of adding executable PHP code into a shortcode attribute, or in content editor in general, you are doing something wrong. You should think again about what, why and how do it. There is a high security risk accepting executable PHP code form user inputs.

Instead, you should pass the post ID in shortcode attributes and get the permalink when parsing the shortcode.

For example, the PHP function that parse the shortcode could be something like this:

add_shortcode( 'button' , 'render_button' );
function render_button( $atts, $content = null ) {

    $atts = shortcode_atts( array(
        'postID' => 0,
        'href'   => '',
        'title'  => ''
    ), $atts );

    //You may need sanitize title, not sure what your needs are
    //change this if you need
    $atts['title'] = sanitize_text_field( $atts['title'] );


    if( (int) $atts['postID'] > 0 ) {

        //If postID is set and greater thant zero, get post permalink for that ID
        //and override href
        $atts['href'] = edit_product_url( $atts['postID'] );
        //For standard posts uncomment next linke
        //$atts['href'] = get_permalink( $atts['postID'] );

    }

    //Example output
    $output="<a class="button" href="" . esc_url( $atts['href'] ) . '">' . $atts['title'] . '</a>';

    return $output;

}

Now you get the functionality without the need of include executable PHP in shortcode attributes. Also, you can use the render_button function directly if you need.

You can use the shortcode in content editor or wherever shortcodes are parsed, for example:

[button title="EDIT" postID="1542"]

You can also render buttons by direct call to the function:

 $button = render_button( array( 'postID' => 4578 ) );
 echo $button;

And if you need a specific href, you can use this shortcode:

 [button title="EDIT" href="http://www.example.com"]

Or with direct function call:

 $button = render_button( array( 'href' => 'http://www.example.com' ) );
 echo $button;

 //Or shorter
 echo render_button( array( 'href' => 'http://www.example.com' ) );

Leave a Comment