Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm using the JSON API and Multiple Featured Images plugins to try and display an image within a Google Map marker. The Multiple Featured Image plugin only stores the Thumbnail ID which I then retrieve from a JSON feed. Unfortunately I can't find a way of getting the image src from just the Thumbnail ID using javascript.

The closest I can get is www.example.com/p=338 but this is of course just the dedicated webpage for displaying images and all I want is the img src. Is their an easy way to do this?

share|improve this question
add comment

1 Answer

I haven't tested this, but you'll probably get the gist of it anyway:

add_action('wp_enqueue_scripts', 'send_image_source_to_js');
function send_image_source_to_js() {
    global $post;

    // Does this post have a featured image? If yes, fetch the link / source
    $has_image = $source = false;
    if($thumb_id = get_post_thumbnail_id($post->ID)) {
        $has_image = true;
        $source_array = wp_get_attachment_image_src($thumb_id, array(300,300));
        $source = $source_array[0];
    }

    // Build an array with what we've found about the post
    $image_params = array(
        'has_image' => $has_image ? 1 : 0,
        'source' => $source ? $source : 0
    );

    // Register, localize and enqueue the script
    wp_register_script('my_script', 'path/to/my_script.js');
    wp_localize_script('my_script', 'image_params', $image_params);
    wp_enqueue_style('my_script');
}

What wp_localize_script does is create a Javascript object which will be printed in your page's html, which you can then use inside your JS code like this (I'm lazy, so I've added a non-sensical jQuery example):

$('#my_image').attr('src', image_params.source);

Let us know how it goes!

share|improve this answer
    
Keep in mind that the global $post is going to be different depending on where you are. On archive pages, it's the first post, for instance (or might not even be property set up). –  chrisguitarguy Feb 9 '13 at 14:54
    
@chrisguitarguy, you're right -- I guess it's not the most foolproof solution, but it's mainly a starting point that shows all the necessary functions and common workarounds for what the user is trying to achieve. –  tbuteler Feb 9 '13 at 16:29
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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