1

This may seem like a Wordpress problem but I think it's PHP specific rather than Wordpress. My problem is in the // Code block I think. Here is my code:

function display_app_rating( $atts ) {

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

// Code
//return '"http://itunes.apple.com/lookup?id='.($app).'"';
$json_url = '"http://itunes.apple.com/lookup?id='.($app).'"';
$json = file_get_contents($json_url);
$result = json_decode($json, TRUE);
foreach ($result['results'] as $key => $value) {
    return '<p class="appstore rating">Average rating '.$value['averageUserRating'].' out of 5 from '.$value['userRatingCount']. ' users.</p><p class="appstore price">Current Price '.$value['currency'].$value['price'].'</p>';
}
}
add_shortcode( 'apprating', 'display_app_rating' );

If I hardcode an app ID as the $app variable it works fine and if I comment my code out and uncomment the return... line it returns the correct URL. My question is how can I get the $app variable appended to the URL and working via my shortcode which is

[apprating app="439438619"]

Any help appreciated.

2
  • 1
    $json_url = "itunes.apple.com/lookup?id=$app" should work. You have single quotes around the string which doesn't inline the variable. I have no experience with wordpress, can you verify that $app is set correctly from the extract? Commented Sep 16, 2014 at 20:32
  • Hi Hammerstein, it doesn't work unfortunately having tried it. When I simply return that line as it is displayed it inlines the URL correctly with the variable inside the quotes as part of the URL. Commented Sep 16, 2014 at 20:51

3 Answers 3

3

I don't think you want to return after each iteration- push the results into a variable and just return once.

$result = json_decode($json, TRUE);
$block = '';
foreach ($result['results'] as $key => $value) {
    $block .='<p class="appstore rating">Average rating '.$value['averageUserRating'].' out of 5 from '.$value['userRatingCount']. ' users.</p><p class="appstore price">Current Price '.$value['currency'].$value['price'].'</p>';
}

return $block;
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you Adam, I may be misunderstanding but I appreciate your input and no doubt your code will improve mine in that block. The problem I have though is getting my $app variable as defined by the shortcode into the URL which happens before this?
It sounds like you should split this function up... try separating this into get_app_rating(), set_app_url(), and display_app_rating() or similar.
I think between you all you've got this working for me thank you very much. I added your block return idea but didn't need to create individual functions.
Right on =) The reason I suggest individual functions is it makes testing easier- something to consider moving forward.
1

Using extract() is not recommended. To check for query values in the URL, use $_GET.

The following first checks if the URL contains ?app_id=something, if so the result will output it. If the URL doesn't contain it, the shortcode attribute will be used [apprating app="something"]. Otherwise, it prints an error message:

add_shortcode( 'apprating', 'shortcode_so_25877611' );

function shortcode_so_25877611( $atts, $content )
{
    $args = shortcode_atts( 
        array(
            'app'   => '',
        ), 
        $atts
    );

    $result = 'No app id.';
    $app = (int) $args['app'];

    if( !empty( $_GET['app_id'] ) )
        $result = (int) $_GET['app_id'];
    elseif( $app )
        $result = $app;

    $json_url = "http://itunes.apple.com/lookup?id=$result";

    return $return;
}

The test shortcode on a post was as follows, and then appending the query var to the URL:

With id: [apprating app="1234"]

Without: [apprating]

PS: as noted by Adam, your return must be outside the foreach loop.

3 Comments

Thank you very much for this. Can you assist further if possible. Where does the rest of my code fit with this? e.g. the $json_url = '"http://itunes.apple.com/lookup?id='.($app).'"'; $json = file_get_contents($json_url); etc I can see the returning of the $app variable but it doesn't appear attached to the URL?
I've added an example. You were using the quotes wrong, learn the difference between single and double quotes in PHP, it's important.
Thank you, I have a working version incorporating your comments. I did think I was using quotes correctly but I wasn't because I was approaching it incorrectly.
0

This is the code I finished up using. It's a mixture of the various responses. Seems to work fine. Guidance appreciated.

add_shortcode( 'myrating', 'display_my_app_rating_89' );
function display_my_app_rating_89( $atts, $content )
{
$args = shortcode_atts( 
    array(
        'app'   => '',
    ), 
    $atts
);

$result = 'No app id.';
$app = (int) $args['app'];

if( !empty( $_GET['app_id'] ) )
    $result = (int) $_GET['app_id'];
elseif( $app )
    $result = $app;

$json_url = "http://itunes.apple.com/lookup?id=$result";
//normal PHP version commented out and wordpress version activated - appears to be Wordpress best practice.
//$json = file_get_contents($json_url);
//wordpress version
$json = wp_remote_retrieve_body (wp_remote_get($json_url));
$result = json_decode($json, true);
$block = '';
foreach ($result['results'] as $key => $value) {
$block .='<span> ... whatever I wanted to return from JSON URL plus my HTML here ... </span>';
}
return $block;
}

3 Comments

I have a supplementary question. One of the fields returned by the JSON URL contains \n for line breaks. This function strips them out and returns a simple block of text. I would like to retain the line breaks - so I guess convert \n to <br> tags. Is there a simple edit to achieve this?
I have tried these methods - stackoverflow.com/questions/5946114/replace-r-n-with-br but with no luck inserting after the line $json = wp_remote_retrieve_body (wp_remote_get($json_url));
Got it - all the sample code was using double quotes, I needed to switch to single for whatever reason $json = str_replace(array('\r\n','\r','\n'),'<br/>', $json);

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.