if is_page() is not working with wp_redirect

I have a plugin installed, which is creating user profiles on frontend. The ID of this page is 301 in backend of wordpress. If a profile site is visited, i want to append the url with a parameter. The parameter value is stored in a cookie. The code for appending the URL is working, but when i add the code to only show on this page id its not working.

The code is executed in my child themes functions.php

NOT WORKING

if( is_page(301)) {
    echo 'page';

// Event ID in der URL als $_GET hinzufügen
function lwb_param_redirect(){
    if( isset( $_COOKIE['lwb_event_id'] ) and !$_GET['event_id'] ) {
        $location = esc_url( add_query_arg( 'event_id', $_COOKIE['lwb_event_id'] ));
        wp_redirect( $location );
    }
}
    add_action( 'template_redirect', 'lwb_param_redirect' );
}

WORKING

// Event ID in der URL als $_GET hinzufügen
function lwb_param_redirect(){
    if( isset( $_COOKIE['lwb_event_id'] ) and !$_GET['event_id'] ) {
        $location = esc_url( add_query_arg( 'event_id', $_COOKIE['lwb_event_id'] ));
        wp_redirect( $location );
    }
}
    add_action( 'template_redirect', 'lwb_param_redirect' );

The working example appends the URL parameter global to all my sites, this i what i want to prevent, because the event_id is only needed on the profile pages.

Topic wp-redirect cookies pages Wordpress

Category Web


In the case of a plugin template, you might find the slug is more reliable for a condition - see below for alternate approach.

When using is_page_template() the parameter passed is anypath/filename.php. Without knowing your file system specifics or the name of the plugin, it is impossible to give you the correct relative path for this. Use plugin_dir_path() to get the plugin root, then subfolder, etc for this approach.

Alternate Approach

Or go with get_page_template_slug() to eliminate the need to know the template location as it only returns the page template filename.

$template = get_page_template_slug(); // You may need to pass the post ID depending on context

if ( 'profile.php' === $template ) {
    echo 'yes';
} else {
    echo 'no';
}

WP Codex for more info: https://developer.wordpress.org/reference/functions/get_page_template_slug/ https://developer.wordpress.org/reference/functions/plugin_dir_path/

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.