How to redirect image attachment to its original post

I’m making a slider that is getting images from attachments in the post. I am trying to rewrite the url for the post so that if someone pastes the direct url to the attachment, it’ll go the post instead of the attachment page. I’ve no idea how to do that.

This site has something like this. click a image on slider, copy the url and paste it and you’ll see it.

Thanks a lot for helping.

EDIT: code for the slider:

<script>
    var clist_autoplay = false;
    var ctemp_autoplay = clist_autoplay;
    jQuery(document).ready(function($) {        
        var larr = {
<?php
$num = 1;
$images = array_values($images);
foreach ($images as $key => $attachment) {
    $image_img = wp_get_attachment_image_src( $attachment->ID, 'large' );
    $alt = get_post_meta($attachment->ID, '_wp_attachment_image_alt', true);
    $image_title = $attachment->post_title;
    $caption = $attachment->post_excerpt;
    $description = $attachment->post_content;     
?>
            "<?php echo $image_title ?>": {
                "0": "<?php echo  $image_img[0] ?>",
                "1": 600,
                "2": 400,
                "3": "<?php echo $image_title ?>",
                "4": "#",
                "5": "<?php echo $image_title ?>",
                "6": "",
                "7": "",
                "8": "",
                "9": "",
                "num": <?php  echo $num++; ?>,
                "slideTitle": "<?php echo $caption ?>",
                "slideContent": "<p><?php echo $description; ?></p>",
                "slideNum": null
                <?php if (isset($images[$key+1])) { ?>
                    , "next": "<?php echo $images[$key+1]->post_title; ?>"
                <?php } ?>
                <?php if (isset($images[$key-1])) { ?>
                    , "prev": "<?php echo $images[$key-1]->post_title; ?>"
                <?php } ?>
                }
<?php } // end foreach ?>
    }
}

I need to put the url in the 4th key so that the image attachemnt link also gets redirected to the post. my demo: http://goo.gl/OsMxe

Answer

You want the permalink for the attachment’s parent post, so, if I am guessing correctly about the contents of $attachment

$parent_url = get_permalink($attachment->post_parent);

Attribution
Source : Link , Question Author : Samia Ruponti , Answer Author : s_ha_dum

Leave a Comment