• Hello everyone, it’s quite surprising (at my level)!

    By looading a plugin I develop, I instantiate an object whose constructor initializes a hook as follows:
    function __construct () {
    add_action ( ‘template_redirect’, array ($this, ‘my_redirect’));
    add_action ( ‘current_screen’, array ($this, ‘my_redirect’));
    }

    The method ‘my_redirect’ overwrites ‘wp_redirect’ as follows:

    ` my_redirect function () {
    …. Some preparation work..
    wp_redirect (admin_url ( ‘profile.php’));
    exit; }`

    This works fine: that is, just after he logs in, the user is redirected to its profile page, in the administration part.

    THEN I tell myself that if I want to redirect to a page in the ‘front-end’, I have to write:
    ` my_redirect function () {

    wp_redirect (site_url ( ‘mypage.php’));
    exit;}`

    Well, no ! the browser returns “page is not redirected correctly!”
    (I precise that the url is valid, of course).

    Would you know why ?? Any help will be greatly appreciated …. thank you in advance
    Pierre

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    The redirect issue is not related to site_url() and admin_url() being used. These functions simply return a particular path, they do no redirecting themselves. I cannot point to exactly where the problem lies, but I’ll try to explain the difference in general terms.

    The ‘template_redirect’ action only fires for front end requests, not back end. The ‘current_screen’ action is the opposite, it only fires for admin requests, not front end. This difference alone could account for the different behavior. ‘template_redirect’ fires on every front end request. When you do a redirect, the server sees it as a new request and fires ‘template_redirect’ again. This causes your redirect code to run and redirect again. Thus the redirects keep occurring into infinity until the browser times out and complains the page is not redirecting properly.

    It may be that the ‘current_screen’ action only fires on the initial request. On redirect, the current screen is known, so the action does not fire again. (I’m guessing on this, I don’t really know, it’s merely an example of how the actions might differ)

    The other possibility is the pages being requested are causing or not causing the associated action to fire again. Two different pages can behave differently in this respect.

    One fix for the front end redirect is to have your my_redirect function() callback remove itself from the action hook as the last thing it does before redirecting. This way the redirect can only occur once because the hook is subsequently removed and unavailable.

Viewing 1 replies (of 1 total)
  • The topic ‘redirection towards site_url doesn't work whereas it's ok with admin_url !’ is closed to new replies.