• Resolved falk07

    (@falk07)


    Hello wp-experts,

    I’ve got a loop with search-results, containing posts, pages and attachments. In case i find an attachment, i’d like to permalink to the containing article – not to the attachment page.
    After a little search in this forum, i tried this peace of code:

    <?php  if(get_post_type() == 'attachment') {
    
    						 echo get_permalink()."<br />";
    						 echo get_permalink($post->post_parent)."<br />";
    						 $parent = get_post($post->post_parent);
    						 echo get_permalink($parent->post_parent);
    					 }
    					?>

    But every line returns the same permalink: the link to the attachment-page.
    Do you have an idea how to do this right?

    Thanks in advance,
    Alex

Viewing 2 replies - 1 through 2 (of 2 total)
  • When I try it the second line works.
    echo get_permalink($post->post_parent)
    But when an attachment is not attached to a post, it returns the same url as the others. This is because no ID will be sent to get_permalink, so it runs exactly the same as the first one. Check that your attachment is attached to a post, that is probably the problem.

    Thread Starter falk07

    (@falk07)

    haha, didn’t see the forest for all the trees ??
    That’s it – thanks a lot for leading me in the right direction!

    Alex

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Find parent post of an attachment’ is closed to new replies.