In my functions.php I have a function that allows me to place a "similar posts by categories":


function alep_related_posts_by_category() {  
global $post;  
// We should get the first category of the post  
$categories = get_the_category( $post->ID );  
$first_cat = $categories[0]->cat_ID;  

$args = array(  
    // It should be in the first category of our post:  
    'category__in' => array( $first_cat ),  
    // Our post should NOT be in the list:  
    'post__not_in' => array( $post->ID ),  
    'posts_per_page' => 3  

$posts = get_posts( $args );  
if( $posts ) {  
    $output = '<div class="sidebar-entries">';  

    foreach( $posts as $post ) {  
        setup_postdata( $post );  
        $post_title = get_the_title();  
        $permalink = get_permalink();  
        $output .= '<p class="title clickablediv"><a href="' . $permalink . '" title="' . esc_attr( $post_title ) . '">' . $post_title . '</a></p>';  
    $output .= '</div>';  
} else {  

    $output .= '<p>Sorry, no other posts matched this category.</p>';  
echo $output;  

I have just found out that if I use this function together with <?php edit_post_link('Edit article', '<p>', '</p>'); ?> it will cause the "Edit post link" to link to the wrong post. I am not sure why these functions are related. I know that if I remove the function above, the edit_post_link will work fine.

So what is going on here? How can I fix this problem?


Use the function wp_reset_postdata() after looping posts.I think this will solve your problem ...

Note : if you use setup_postdata() you do need to wp_reset_postdata() afterwards.

|improve this answer|||||
  • So I added wp_reset_postdata() after echo $output;. Is this what you meant? I mean does it matter where in the code I add it, as long as it is after setup_postdata()? – Arete Dec 14 '16 at 13:11

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.