简体   繁体   中英

highlighting current post in recent posts sidebar , wordpress

Im just wondering how I could get the post id of the blog post I am currently reading while in another loop (ie the recent posts loop in the sidebar)

In my single post php file I have this code creating a variable

<?php while ( have_posts() ) : the_post(); ?>

                <?php get_template_part( 'content', 'single' ); ?>
                <?php $current_post_id = get_the_ID(); ?> 


            <?php endwhile; // end of the loop. ?>

Then in my default-widgets php file, in the loop for recent posts I have this...

<?php  while ($r->have_posts()) : $r->the_post(); ?>
    <?php $recent_post_id = get_the_ID(); ?>

    <li> <?php echo $recent_post_id; if ( $recent_post_id == $current_post_id ) { echo 'pass   '; } else { echo 'fail   ';} ?></li>
    <?php endwhile; ?>

Its giving fail every time, so obviously what Im doing doesnt make sense (Im still learning). Im just wondering is there a way to grab the post id from the first loop, and use it in the second. At the moment when I echo current_post_id in the second loop nothing shows up. (Regarding highlighting the current post, that'll be easy once I get this working.

Thanks for the help.

There are a lot of examples online on how to get the ID outside the loop.

try this in the widget code:

    <?php  


    global $post;
    $current_post_id = $post->ID;


while ($r->have_posts()) : $r->the_post(); ?>


        <li> <?php echo $recent_post_id; if ( $recent_post_id == $current_post_id ) { echo 'pass   '; } else { echo 'fail   ';} ?><a href="<?php the_permalink() ?>" title="<?php echo esc_attr(get_the_title() ? get_the_title() : get_the_ID()); ?>"><?php if ( get_the_title() ) the_title(); else the_ID(); ?></a></li>
        <?php endwhile; ?>

Let us know if it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM