Search code examples
jquerywordpresspinterest

How could I use jQuery .closest() to determine nearest image and pass the path to PHP function


I am trying to write a Wordpress shortcode that will be smart enough to find the closest image to the shortcodes placement inside the HTML view.

I would like to use jQuery to determine what the nearest image is and then pass it to the function below. I should mention that it is possible for the shortcode to be used multiple times in a post.

I have looked into using .closest() to achieve this but I am unsure how to pass this information to my function.

function pinterest_post() {

global $post;
$icon_url = urlencode(site_url().'/wp-content/themes/Kin/images/pinterest.png');
$posturl = urlencode(get_permalink());
$pinurl = 'http://pinterest.com/pin/create/button/?url='.$posturl.'&media='.$icon_url;
$pinurl .= '&description='.urlencode(get_the_title());

return '
    <div class="pinterest_post">
        <a href="'.$pinurl.'"><img src="/wp-content/themes/Kin/images/pinterest.png"/></a>
    </div>';
}

add_shortcode('pin', 'pinterest_post');

Any suggestions to achieve this would be much appreciated.


Solution

  • After rethinking my approach I found it to be the easiest to allow the user to specify the URL of the image as a parameter of the shortcode. This will ultimately give them greater control over which image is shown and would prevent having to transverse the DOM multiple times for each instance of [pin] in a post.

    My modified function and example usage:

    function pinterest_post($atts = '') {
    
        global $post;
    
        $image_fallback = get_bloginfo(template_url).'/images/logo-green-for-website.gif';
        $icon_url = get_bloginfo(template_url).'/images/pinterest.png';
    
        extract(shortcode_atts(array('path' => $image_fallback,), $atts));
        $image_url = $path;
    
        $posturl = urlencode(get_permalink());
    
        $pinurl = 'http://pinterest.com/pin/create/button/?url='.$posturl;
        $pinurl .= '&description='.urlencode(get_the_title());
        $pinurl .= '&media='.$image_url;
    
        return '
            <div class="pinterest_post">
                <a href="'.$pinurl.'"><img src="'.$icon_url.'"/></a>
            </div>';
    }
    
    add_shortcode('pin', 'pinterest_post');
    

    Usage inside a Wordpress post:

    [pin path="http://www.site.com/image.jpg"]