代码的问题是$wp_query
是全局变量。通过函数加载侧栏后(dynamic_sidebar
) 在使用之前,您需要将该变量全球化。
但是,一旦您在单视图中,当前的\\u post始终为0。您必须运行另一个查询,循环它,并将此查询中的每个帖子id与原始查询的帖子id进行检查,直到找到正确的索引。
最终使用前setup_postdata
全球化是一种很好的做法$post
循环启动前变量和重置后数据(带wp_reset_postdata
) 循环结束后。
之前的所有提示都放在一起(未经测试):
<?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="<?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>