I am trying take an action based on a specific word present in the URL. For that I am looking at 2 options, 1 via pre_handle_404 filter and other via wp action.
The problem I am facing is that $wp->request is returning just the home page url and not the full URL so my if condition is never satisfied. The code that I have tried for the both is:
pre_handle_404
add_filter( 'pre_handle_404', 'my_filter_pre_handle_404', 1, 2 );
function my_filter_pre_handle_404( $preempt, $wp_query ) {
global $wp;
if (str_contains($wp->request, '/page/')) {
global $wp_query;
$wp_query->set_404();
status_header( 404 );
}
return $preempt;
}
wp action
add_action( 'wp', 'my_action_wp', 1 );
function my_action_wp( $wp ) {
global $wp_query;
if (str_contains($wp->request, '/page/')) {
global $wp_query;
$wp_query->set_404();
status_header( 404 );
}
}
I tried to replace $wp->request based if condition with the following but still didn’t help:
$current_url = home_url(add_query_arg(array(), $wp->request));
if (str_contains($current_url, '/page/')) {
Please help to get the current full url of he page in either of the above (pre_handle_404 filter or wp action)