0

I am trying to create a simple Wordpress shortcode based function that will take a defined number and convert it to the end user's local currency. Where I am stuck is how to search the post for the shortcode because the defined number is subject to change. If someone could please let me know how best to extract the number as a variable, I can then run it through the exchange rate function (which works fine, I have tested it with custom field stored data).

{customShortcode - priceAdditions [400]}

I have tried to explode() it around the [] and that seems to show promise but I can't work out how to extract it, also with the prospect of more than one instance of this being used with different numbers. I think regex or preg_match may be the way to go but I don't quite understand that just yet.

If you need more info, please let me know. Thanks in advance.

Dan

Edit - The function for the shortcode that works -

$thePostContent =   get_the_content($post->ID); 
$thePostContent =   str_replace('{customShortcode - price}',thePrice(),$thePostContent);

The function -

function thePrice(){
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
$Exploded_URL = explode("/",$pageURL);
if      ($Exploded_URL[4] == ''){$thePostIsIn   =   217;}
elseif  ($Exploded_URL[4] == 'productA'){$thePostIsIn   =   347;}
elseif  ($Exploded_URL[4] == 'productB'){$thePostIsIn   =   345;}
else    {$thePostIsIn   =   217;}
if      (empty($_COOKIE['userLocate']) || $_COOKIE['userLocate'] == 'US' || ($_COOKIE['userLocate'] != 'EU' && $_COOKIE['userLocate'] != 'AU' && $_COOKIE['userLocate'] != 'GB')){
    $currencyCode   =   'USD';
    $currencyPrefix =   '$';
}
elseif  ($_COOKIE['userLocate'] == 'EU'){
    $currencyCode   =   'EUR';
    $currencyPrefix =   '€';
}
elseif  ($_COOKIE['userLocate'] == 'AU'){
    $currencyCode   =   'AUD';
    $currencyPrefix =   'A$';
}
elseif  ($_COOKIE['userLocate'] == 'GB'){
    $currencyCode   =   'GBP';
    $currencyPrefix =   '£';
}
else {
    $currencyCode   =   'USD';
    $currencyPrefix =   '$';
}

$args=array(
'post_type' =>'page',
'post__in' => array($thePostIsIn)
);
$recent_posts = get_posts($args);
foreach( $recent_posts as $recent ){    

    $mypages        =   get_post( $recent->ID );
    $theBaseRate    =   get_post_meta($recent->ID, "Payment Cost",1);

    if(get_post_meta($recent->ID, "Payment Period",1)){
        $payPeriod  =   get_post_meta($recent->ID, "Payment Period",1);
    }
    else{
        $payPeriod  =   "per month";
    }

    $rssFeedUrl     =   "http://themoneyconverter.com/rss-feed/GBP/rss.xml";
    $rss            =   simplexml_load_file($rssFeedUrl);
    foreach($rss->channel->item as $feedItem){
        $currency   =   explode('/',$feedItem->title);
        if(strpos($currency[0], $currencyCode )!== false){
            $content    =   $feedItem->description;
            $content    =   explode('= ',$content);
            $content    =   substr($content[1],0,7);
            $theCost    =   $theBaseRate * $content;
            $theCost    =   number_format($theCost, 2, '.', '');
        }
    }
}
echo '<p class="rentCost"><span class="rentalCost">'.$currencyPrefix.$theCost.' '.$payPeriod.'</span></p><div class="clear"></div>';
}
6
  • Can you provide your shortcode code? Commented Jan 29, 2013 at 16:23
  • {customShortcode - priceAdditions [400]} Commented Jan 29, 2013 at 16:26
  • The one that works, with the number in the custom field is {customShortcode - price[$customFieldMetaPrice]}, but as this one is in the actual post, I can't seem to work out how to specifically take a price given to convert it to the end-user's local currency Commented Jan 29, 2013 at 16:27
  • Shortcodes usually look like [myshortcode param1="something" param2="something else"] in the editor and you should have a function defined for the shortcode. Can you show me the function defined for the shrotcode? Commented Jan 29, 2013 at 16:29
  • I'm aware of that, but I decided to use curleys so that they are obviously different from a WP plugin's shortcode. Shortcode in retrospect is probably the wrong term. I've updated the question. Commented Jan 29, 2013 at 16:36

2 Answers 2

4

You should use the built-in shortcode api from wordpress.

In your functions.php

function thePrice( $atts ) {


   extract( shortcode_atts( array(
        'price' => 0 //default price
    ), $atts ) );

    //$price is now available and will hold the user entered price 
    //in the example below this would be 400

    /*
     Your conversion code here
     */

}

add_shortcode( 'convert_price', 'thePrice' );

How to use the shortcode in the editor

[convert_price price="400"]

Now you can simply use the_content() in your template loop and the shortcodes will be properly rendered.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Jrod. This makes MUCH more sense, tying myself up in knots. Is there a way of being able to use this more than once in a post? Functions cannot be re-declared.
2

I know where you're trying to go with the custom shortcode, but why don't you stick with Wordpress's build-in machinery for shortcodes and let it do the heavy lifting? The official docs say

"The API handles all the tricky parsing, eliminating the need for writing a custom regular expression for each shortcode. Helper functions are included for setting and fetching default attributes."

Your code could become:

[priceAdditions price="400"]

and with a short little addition to functions.php, you could get your data.

2 Comments

Thanks @jnunn. Sorry, I tied myself up in a knot for no apparent reason here!
I've done similar :) I'm finding most of the time reinventing the wheel is a waste of my time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.