Create a Wordpress shortcode using PHP [duplicate]

I am currently using the following code within single.php (after the_content)
This gets the store_name from custom field as $merchant from the post and then returns a list of products from that merchant from and external script.

$merchant = get_field('store_name');
echo '<h3> Random products from ' . get_field('store_name') . '</h3>';
$external_baseHREF = "";
$external_path = "/home/website/public_html/store/";
$_GET["q"] = "merchant:".$merchant;

This is working fine, however I cannot move the position of where the products are appearing, they currently appear after the main post.

I would like to have them appearing further up the post, and one solution I have considered is adding them via a shortcode so I can position them as I like eg
[merchant-name merchantname=”Adidas”] or something similar

Can you please assist in creating this shortcode? Or offering alternative solution.


1 Answer

This is a basis of the shortcode to be placed in your functions.php or custom plugin. You will need to edit it to fit your needs:

//Shortcode function can be called whatever you want
function merchantname_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        //Creates a arg "merchantname" with no default value. 
        //To use this arg in your shortcode use: $atts['merchantname']
        'merchantname' => ''
    ), $atts, 'merchant-name' );

    //Anything else you want goes in here. You can't echo anything in a shortcode. 
    //Assign it to a var like: 
    $String = "foo"; 
    $String .= "bar"; 

    return $String; 

    //Anything that is echoed will be displayed at the top of $content regardless 
    //to where the shortcode is.

//First arg is the text you would put in your page to display the shortcode. 
//Creates a shortcode [merchant-name]. 
//Second arg is the function used to create the shortcode.
add_shortcode( 'merchant-name', 'merchantname_shortcode' );

Shortcode Codex Page

Leave a Comment