开发者

Losing reference to $_post variable?

In the code below, the echo at the top returns true, but the echo at the bottom returns nothing. Apparently the code in between is causing me to lose a reference to the $_post variable?

<?php
echo "in category: ".in_category('is-sidebar'); //RETURNS TRUE
if (!get_option('my_hide_recent'))
{
    $cat=get_cat_ID('top-menu'); 
    $catHidden=get_cat_ID('hidden');
    $myquery = new WP_Query();
    $myquery->query(array(
        'cat' => "-$cat,-$catHidden",
        'post_not_in' => get_option('sticky_posts')
    ));
    $myrecentpostscount = $myquery->found_posts;
    if ($myrecentpostscount > 0) 
    { ?>
    <div class="menu"><h4><?php if ($my_sidebar_heading_recent !=="") { echo $my_sidebar_heading_recent; } else { echo "Recent Posts";} ?></h4><ul>
    <?php 
    global $post; 
    $current_page_recent = get_post( $current_page );
    $myrecentposts = get_posts(array('post_not_in' => get_option('sticky_posts'), 'cat' => "-$cat,-$catHidden",'showposts' => $my_recent_count));
    foreach($myrecentposts as  $idxrecent=>$post) {
        if($post->ID == $current_pag开发者_开发百科e_recent->ID)
            {
                $home_menu_recent = ' class="current_page_item';
            } 
            else 
            {
                $home_menu_recent = ' class="page_item';
            }
            $myclassrecent = ($idxrecent == count($myrecentposts) - 1 ? $home_menu_recent.' last"' : $home_menu_recent.'"'); 
        ?>
    <li<?php echo $myclassrecent ?>><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php 
    } ; if (($myrecentpostscount > $my_recent_count) && $my_recent_count > -1){ ?><li><a href="<?php bloginfo('url'); ?>/site-map">View all</a></li><?php } ?></ul></div>
<?php 
}
} 
global $sitemap;
echo "in category: ".in_category('is-sidebar'); //RETURNS NOTHING


Variables in PHP are case-sensitive. This means that $_POST (a predefined variable) is not the same as $_post.

If you really did mean $_post, it's a terrible variable name, as it may confuse things later on.


Your foreach $myrecentposts declares a new variable $post. Use a different name for $post there.


The special variable that contains the current post is called $post, not $_post. But since that's the default value for in_category() anyway, you don't need to pass it that second parameter.

But you need to add a call to setup_postdata($post) inside that foreach loop to, well, setup the post data. Without it the "magic" functions like the_title() will just keep returning the post data for the original post. Note that that variable must be called $post.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜