将单篇文章固定链接重定向到分页分类页面

时间:2013-03-15 作者:Squrler

有没有可能从permalink(一篇文章)重定向到相关类别页面中的同一篇文章,这可能是分页的?

所以当人们访问http://domain/post_number 他们被重定向到http://domain/category/page/2/#post_number?

1 个回复
最合适的回答,由SO网友:Squrler 整理而成

我找到了一个有效的解决方案!代码可以改进,但这只是一个开始。

把这个放进去single.php:

<?php /* 1. First check to see if single is in the category that is not allowed to be viewable through the single template: */  
if (in_category(\'in-het-kort\') ) {

/* 2. Do a loop to determine how many posts there are in a certain category. */
$args=array(
    \'cat\'       => 1036,
    \'showposts\' => -1
);

$count=0;

$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {

    while ($my_query->have_posts()) : $my_query->the_post();

        /*Find out what the offset is for the current post */
        $count++;
        if ( $current_post == get_the_ID() ) {
            $post_offset = $count;
        }

    endwhile;

} 
wp_reset_query();

?>

<?php /* 3. Then construct the URL to redirect to. */ ?>

<?php 
$postsperpage = get_option(\'posts_per_page\');
$cat_page_number_notrounded = $post_offset / $postsperpage;
$cat_page_number = round($cat_page_number_notrounded, 0, PHP_ROUND_HALF_UP);
$redirect_url = get_bloginfo(\'url\').\'/categorie/in-het-kort/page/\'.$cat_page_number.\'#post_\'.get_the_ID();
?>

<?php /* 4. Then redirect the user to this URL either via Javascript... */  ?>   
<script>
window.location = "<?php echo $redirect_url; ?>"
</script>

<?php /* 5. ...Or via PHP, depending on your needs. */ ?>
<?php wp_redirect($redirect_url); exit; ?>

结束

相关推荐

使用`auth_reDirect`:即使我已经登录,也一直要求我登录

我正在尝试使用auth_redirect 在访问特定页面时自动重定向未登录的访问者。以下是我使用的代码:add_action(\'template_redirect\',\'wpse16975_check_if_logged_in\'); function wpse16975_check_if_logged_in(){ $pageid = 29; if(is_page($pageid)) auth_redirect(); } 重定向工作正常(我看到