0

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?

2

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!

  • 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. – Tomas Buteler Feb 9 '13 at 16:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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