Skip to content

Instantly share code, notes, and snippets.

@lelandf
Created September 29, 2021 14:30
Show Gist options
  • Save lelandf/0d813cdaca27aee3dc9602d6daa7606f to your computer and use it in GitHub Desktop.
Save lelandf/0d813cdaca27aee3dc9602d6daa7606f to your computer and use it in GitHub Desktop.
[TEC] working redirect sample
<?php
add_action( 'template_redirect', function() {
if ( is_user_logged_in() ) {
return;
}
if (
tribe_is_event() ||
tribe_is_event_category() ||
tribe_is_in_main_loop() ||
tribe_is_view() ||
'tribe_events' === get_post_type() ||
is_singular( 'tribe_events' )
) {
$location = home_url( '/my-account/' );
$location = wp_sanitize_redirect( $location );
header( 'Location: '. $location, true, 302 );
exit;
}
} );
@lelandf
Copy link
Author

lelandf commented Sep 29, 2021

Alternative while tacking on $wp->request path as an encoded query argument:

add_action( 'template_redirect', function() {
	if ( is_user_logged_in() ) {
		return;
	}
	
	if (
		tribe_is_event() ||
		tribe_is_event_category() ||
		tribe_is_in_main_loop() ||
		tribe_is_view() ||
		'tribe_events' === get_post_type() ||
		is_singular( 'tribe_events' )
	) {
		global $wp;
		$redirect = trailingslashit( home_url() ) . $wp->request;
		
		$location = home_url( '/my-account/' );
		$location = add_query_arg( 'redirect_to', urlencode( $redirect ), $location );
		$location = wp_sanitize_redirect( $location );
		
		header( 'Location: '. $location, true, 302 );
		exit;
	}
} );

@lelandf
Copy link
Author

lelandf commented Sep 30, 2021

Alternative while tacking on query arguments to URL:

add_action( 'template_redirect', function() {
	if ( is_user_logged_in() ) {
		return;
	}
	
	if (
		tribe_is_event() ||
		tribe_is_event_category() ||
		tribe_is_in_main_loop() ||
		tribe_is_view() ||
		'tribe_events' === get_post_type() ||
		is_singular( 'tribe_events' )
	) {
		$redirect = untrailingslashit( home_url() ) . filter_input( INPUT_SERVER, 'REQUEST_URI' );
		
		$location = home_url( '/my-account/' );
		$location = add_query_arg( 'redirect_to', urlencode( $redirect ), $location );
		$location = wp_sanitize_redirect( $location );
		
		header( 'Location: '. $location, true, 302 );
		exit;
	}
} );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment