Redirect a page id url but not the page slug

My client is asking me to force a 404 $wp_query->set_404(); if the URL is example.com/page_id=342 but DON’t redirect if the URL is example.com/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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x