Get the index of post outside the loop

The problem of your code is that $wp_query is a global variable. Once the sidebar is loaded via a function (dynamic_sidebar) you need to globalize that variable before use.

However, once you are in the single view the current_post is always 0. You have to run another query, loop it, and check the every post id in this query against the original queried post id, until you find the right index.

Finally before use setup_postdata is a good practise globalize $post variable before loop start and reset post data (with wp_reset_postdata) after the loop end.

All previous tips putted together (untested):

<?php
// put this function in any accessible place, like functions.php or plugin...
function get_post_index ( $posts = array(), $vs = 0) {
  if ( empty($posts) ) return -1;
  $i = 0;
  foreach ( $posts as $one ) {
    if ( $one->ID == $vs ) return $i;
    $i++;
  }
  return -1;
}
?>

<ul>
<?php
$paged = 1;
if ( is_single() ) {
  // get ALL the posts in current category
  $all = get_posts( array('category' => $cat_id, 'posts_per_page' => -1) );
  // use the function 'get_post_index' to retrive the post index
  $index = get_post_index( $all, get_queried_object()->ID );
  if ( $index != -1 ) {
    global $wp_query;
    $perpage = $wp_query->get('posts_per_page') ? : get_option('posts_per_page');
    // get the paged value as ceil of index / posts_per_page
    // e.g. if index is 13 and posts_per_page is 6 it's = ceil(2.1666) = 3
    $paged = ceil( $index / $perpage );
    if ( $paged == 0 ) $paged = 1;
  }
}
$args = array('paged' => $paged );
if ( is_tag() ) {
  $args['tag'] = get_queried_object()->slug;
} else {
  $args['category'] = $cat_id;
}
$myposts = get_posts( $args );
if ( ! empty($myposts) ) :
  $i = 0;
  global $post;
  foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
  <li>
  <?php if (is_blog()) { ?>
    <a href="https://wordpress.stackexchange.com/questions/114308/<?php the_permalink(); ?>"><?php the_title(); ?></a>
  <?php } else { ?>
    <a href="#" onclick="goTo(<?php echo $i; ?>);return false;"><?php the_title(); ?></a>
  <?php } ?>
  </li>
<?php $i++; endforeach; wp_reset_postdata(); endif; ?>
</ul>

Leave a Comment

tech