Hook template_redirect

CAUTION : this post is only for developers !

This hook « template_redirect » is a very powerful action : in the following example, the code is added in the function.php of the current theme.

FIRST EXAMPLE

function redirect_action () {
global $posts,$post;
if (is_single() && in_category(29)):
header("location:".get_settings('home')."/?cat=29&pid=".$post->ID."#choice");
exit;
endif;
}
add_action('template_redirect','redirect_action');

In this example and this theme, a single of category 29 can only be see in a special DIV of the category-29 page anchored #choice… (the DIV contain a get_posts of this post)

SECOND EXAMPLE

This hook can be use if you change the place (ISP or Domain) of a WP site. During the intermediate phase, on the old site in the function.php ot the current theme, you add a function like that. All old URLs memorized in Robots like Google are redirected to the new site (here: subdomain.newdomain.tld).

function redirect_action () {
global $posts,$post,$cat;
if (is_single()):
header("location:http://subdomain.newdomain.tld/?p=".$post->ID);
exit;
elseif (is_page()):
header("location:http://subdomain.newdomain.tld/?page_id=".$post->ID);
exit;
elseif (is_category()):
header("location:http://subdomain.newdomain.tld/?cat=".$cat);
exit;
endif;
}
add_action('template_redirect','redirect_action');

THIRD EXAMPLE

To insert this example to patch a cookies problem, please verify if you use « Login Widget » with WP 2.3.2 and this action (hook) is not use elsewhere :

function login_patch_widget () {
global $posts,$post;

widget_sidebarLogin_start();
/*send cookies if no logged for sidebarlogin - you can add conditional depending of type of page with conditional tag like is_page() depending of your theme*/
}
add_action('template_redirect','login_patch_widget');

Don’t forget to delete (by commenting) the add_action(‘authenticate », »widget_sidebarLogin_start ») in the plugin…

AGAIN : CAUTION : this post is only for developers !

Ce contenu a été publié dans Studies, avec comme mot(s)-clé(s) , , , . Vous pouvez le mettre en favoris avec ce permalien.