最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

404 error - Redirect a page id url but not the page slug

programmeradmin1浏览0评论

My client is asking me to force a 404 $wp_query->set_404(); if the URL is example/page_id=342 but DON't redirect if the URL is example/about even though they are the same page. I have to do this in the functions.php file and not .htaccess.

I have tried:

add_action('init','add_get_val');
function add_get_val() { 

if (isset($_GET['page_id'])) {
    $param = $_GET['page_id'];
  
    if($param == '342') {
         global $wp_query;
           $wp_query->set_404();
           // status_header( 404 );
           // get_template_part( 404 ); 
           // exit();
    }

}

}

The code as it stands does not work. But if I uncomment the status_header(), get_template(), and exit() it does. However, it does not give the same 404 page.

What am I doing wrong?

My client is asking me to force a 404 $wp_query->set_404(); if the URL is example/page_id=342 but DON't redirect if the URL is example/about even though they are the same page. I have to do this in the functions.php file and not .htaccess.

I have tried:

add_action('init','add_get_val');
function add_get_val() { 

if (isset($_GET['page_id'])) {
    $param = $_GET['page_id'];
  
    if($param == '342') {
         global $wp_query;
           $wp_query->set_404();
           // status_header( 404 );
           // get_template_part( 404 ); 
           // exit();
    }

}

}

The code as it stands does not work. But if I uncomment the status_header(), get_template(), and exit() it does. However, it does not give the same 404 page.

What am I doing wrong?

Share Improve this question edited Feb 17, 2021 at 8:24 MrWhite 3,8911 gold badge20 silver badges23 bronze badges asked Feb 17, 2021 at 0:04 JasonJason 2052 silver badges12 bronze badges 1
  • "if the url is example/page_id=342" - presumably you mean .../?page_id=342? If they are the "same page", why wouldn't you redirect one to the other? – MrWhite Commented Feb 17, 2021 at 8:30
Add a comment  | 

1 Answer 1

Reset to default 2

Try using the pre_handle_404 hook instead:

add_filter( 'pre_handle_404', 'wpse_383506', 10, 2 );
function wpse_383506( $preempt, $wp_query ) {
    if ( ! empty( $_GET['page_id'] ) &&
        '342' === $_GET['page_id']
    ) {
        // Throw a 404 error.
        $wp_query->set_404();

        // And prevent redirect to the page permalink (pretty URL).
        remove_action( 'template_redirect', 'redirect_canonical' );
    }

    return $preempt; // always return it
}
发布评论

评论列表(0)

  1. 暂无评论