Dynamic highlight not working (8 posts)

  1. rodrego
    Posted 2 years ago #

    Hi folks,

    I'm trying to highlight the current post in a dynamic menu but WordPress is beating me on this.

    The problem is the menu is totally dynamic. Items can be added to it. So the WordPress default solution doesn't work. I used the solution proposed in this post, but it's not working: http://wordpress.org/support/topic/highlighting-current-post-title-in-get_posts-list?replies=8#post-1130031

    Here's my code. What's wrong?

    <ul id="2">
        $IDOutsideLoop = $post->ID;
        global $post;
        $args = array( 'numberposts' => 500, 'category' => 3 );
        $myposts = get_posts( $args );
        foreach( $myposts as $post ) :	setup_postdata($post); ?>
           <li<?php if($IDOutsideLoop == $post->ID) { echo " class=\"current\""; } ?>>
               <a href="<?php the_permalink(); ?>" >
    		<?php the_title(); ?>
    <?php endforeach; ?>
  2. bcworkz
    Posted 2 years ago #

    I'm guessing that for your situation, the current post ID is not contained in $post->ID when the line $IDOutsideLoop = $post->ID; is executed, otherwise this solution should work.

    Assuming of course you have properly set up the CSS for li.current to be highlighted.

  3. rodrego
    Posted 2 years ago #

    Hi, bcworkz, thanks for your answer.

    If I put the line $IDOutsideLoop = $post->ID; inside the "foreach" command, all
    li tags get the "current" attached to it. If I put it outside, no matter where, then none get it...

    Is there a different way to do it?

  4. bcworkz
    Posted 2 years ago #

    For whatever reason, $post does not contain the current post object for your application. You need to find a different way to identify the current post. Maybe $IDOutsideLoop = get_the_ID(); ? (FWIW, blindly using $post is a bit hacky anyway)

  5. rodrego
    Posted 2 years ago #

    Doesn't work... It seems like get_the_ID; only works inside the loop, which is not my case?

    Please let me know if you have any more ideas... Kind of stuck with that.

  6. bcworkz
    Posted 2 years ago #

    Right, inside loop only. You'll need to examine the source code to find some sort of post identifying information. It has to exist in some form to get the current post out of the DB.

  7. tweetpressfr
    Posted 2 years ago #

    Hi Rodrego

    $IDOutsideLoop = $post->ID;
    if($IDOutsideLoop == $post->ID)

    I don' get it. What do you want to do? This if statement is wrong, useless at best.

  8. rodrego
    Posted 2 years ago #

    Hi jmlapam,

    I copied it from a working code (at least they say so at the thread): http://wordpress.org/support/topic/highlighting-current-post-title-in-get_posts-list?replies=8#post-1130031

    Maybe I did something wrong. How can I make it work?

Topic Closed

This topic has been closed to new replies.

About this Topic