【问题标题】:Redirect Duplicated URL in Wordpress Customized Permalinks在 Wordpress 自定义永久链接中重定向重复的 URL
【发布时间】:2016-06-14 17:45:21
【问题描述】:

我想问你一些我真正难以解决的问题。我的 wordpress 网站有问题,它的 URL 重复,结果相同。

  1. www.site.com/some-blog-post
  2. www.site.com/news/some-blog-post

当我修改我的主题功能时,我得到了数字 2:

add_action( 'init', 'add_news_slug_permalink', 1 );
function add_news_slug_permalink() {
    register_post_type( 'post', array(
        'rewrite' => array( 'slug' => 'news'    ),
    ) );
}

问题是,如何将没有news slug 的URL 重定向或禁用到带有news slug 的URL? 谢谢。

【问题讨论】:

  • 最坏的情况,您可以通过修改 .htaccess 文件来做到这一点。添加重写条件。
  • @Rasclatt 你能给我样品吗?

标签: php wordpress .htaccess permalinks


【解决方案1】:

我得到了解决方案,在这种情况下,我在 function.php 中添加了一个操作,就像:

add_action('template_redirect', 'redirect_to_news_slug', 20);

function redirect_to_news_slug() {

    global $post;

    /**
     * Check if the page is single Post
     */
    if ($post->post_type == 'post' && (is_category() == false) &&
        (is_single() == true) && (is_home() == false)) {

        $currentUrl = $_SERVER["REQUEST_URI"];

        /**
         * Remove slash from URL, and get the first slug
         */
        $partOfUrl = array_filter(explode('/', $currentUrl));

        /**
         * Check if URL doesn't have 'news'
         */
        if ($partOfUrl[1] !== 'news') {

            /**
             * set new URL with 'news' slug
             */
            $newUrl = home_url().'/news/' . $partOfUrl[1];

            /**
             * Redirect to new URL
             */
            wp_redirect( $newUrl,301 );
            exit;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2013-08-14
    • 2016-02-11
    • 2017-12-20
    • 2015-12-04
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 2019-07-08
    相关资源
    最近更新 更多