0

I use get_posts() to generate a menu of posts having the current page as the parent. This causes the post_id to be set to the first such post, instead of the original page's post_id. I.e. I want Wordpress to continue as if nothing happened after the query.

This is the code I use in sidebar.php:

$args = array(
'posts_per_page'   => -1,
'offset'           => 0,
'category'         => '',
'orderby'          => 'title',
'order'            => 'ASC',
'include'          => '',
'exclude'          => '',
'meta_key'         => '',
'meta_value'       => '',
'post_type'        => $slug,
'post_mime_type'   => '',
'post_parent'      => '',
'post_status'      => 'publish',
'suppress_filters' => true );

$pt=get_the_title();
$posts=get_posts($args);
//loop children custom posts.
if ($posts) {
    echo '<div class="generated-menu">';
    echo '<ul class="left-navigation"><li class="active"><a href="/'.$slug.'">'.$m.'</a>';
    // Start the Loop.
    foreach ($posts as $p) {

        $t=get_the_title($p->ID);
        $l=get_permalink($p->ID);
        $a='';if ($t==$pt) $a=' class="active"';
        echo '<ul><li'.$a.'>';
        echo '<a href="'.$l.'">'.$t.'</a>';
        echo '</li></ul>';

    }   //foreach
    echo '</li></ul></div>';
}   //if has posts

All available information says get_posts() doesn't affect anything. Well, that's confirmed to be a lie, unless you can spot an error in my code.

If I comment out the single line $posts=get_posts($args);, main content is OK.

I have tried using wp_reset_postdata(), no difference.

Thankful for any help by the pros here :)

5
  • This looks ok. Are you confident that this is the portion of code that causes ID to change? Is it changed if you dump it right after this?
    – Rarst
    Jan 31, 2014 at 16:55
  • 1
    possibly the use of $posts might be interfering; try to change that to something else like $menu_posts or similar, and try what @Shellbot suggested.
    – Michael
    Jan 31, 2014 at 17:28
  • If I comment out the single line $posts=get_posts($args);, main content is OK. Feb 3, 2014 at 7:08
  • @Michael, you spotted the name conflict! If I refrain from using $posts as variable name, it works. Add it as answer and I'll accept it. Feb 3, 2014 at 7:34
  • I'll put that as an answer so the topic can be marked as solved (just for the forum staistics)
    – Michael
    Feb 3, 2014 at 12:14

2 Answers 2

1

the use of $posts might be interfering; try to change that to something else like $menu_posts or similar.

0

You need to reset the query after your if statement.

<?php wp_reset_postdata(); ?>

See if that does the trick.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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