【问题标题】:PHP Wordpress Simple Redirect by Custom Fields自定义字段的 PHP Wordpress 简单重定向
【发布时间】:2017-11-04 21:08:54
【问题描述】:

我需要检查用户是否已登录,根据结果,我希望将用户重定向到自定义字段 A 或 B。这是我目前的代码:

<?php

    global $current_user;
    get_currentuserinfo();
    require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-config.php');

    add_action('get_header', 'redirect');

    function redirect () {
        global $post;
        if (is_page() || is_object($post)) {
            if (get_post_meta($post->ID, 'redirect', true)) {
                header('Location: ' . get_post_meta($post->ID, 'redirect', true));
            }
        }
    }

    function redirect_b () {
        global $post;
        if (is_page() || is_object($post)) {
            if (get_post_meta($post->ID, 'Shortlink', true)) {
                header('Location: ' . get_post_meta($post->ID, 'Shortlink', true));
            }
        }
    }

    if ($current_user->ID == '') { 
        redirect();
}
else { 

    redirect_b();
}

?>

它不起作用,每当我激活它时都会收到错误 500。谁能帮我?非常感谢!

【问题讨论】:

  • header 调用之后添加exit;,在调用重定向之前不要渲染任何东西。
  • 下面的答案很好,但供您参考,此代码永远不会评估为真。如果当前用户未登录,则当前用户 id 为 0 if ($current_user->ID == '')

标签: php wordpress redirect


【解决方案1】:

最好使用wp_safe_redirect() 来避免打开重定向。在这种情况下,不必使用它,因为它不是来自用户输入,但我喜欢始终使用此功能。并不是说wp_safe_redirect() 不会自动退出,所以应该始终跟在退出调用之后。

function redirect_site_user() {

    global $post;

    if ( is_user_logged_in() ) {

        if ( get_post_meta($post->ID, 'Shortlink', true) ) {
            wp_safe_redirect( get_post_meta($post->ID, 'Shortlink', true) );
        }


    } else {
        if ( get_post_meta($post->ID, 'redirect', true) ) {
            wp_safe_redirect( get_post_meta($post->ID, 'redirect', true) );
        }
    }

    exit;
}

add_action( 'init', 'redirect_site_user' );

【讨论】:

  • 非常感谢您帮助我!但这并没有真正起作用,它没有重定向到自定义字段上的 URL
  • 检查 get_post_meta 函数是否返回任何数据。
  • 好像不是。
【解决方案2】:

不要使用get_currentuserinfo(),因为它已被弃用。您应该改用wp_get_current_user()。但在您的示例中,我们甚至不需要它,因为 is_user_logged_in() 已经使用该函数来确保设置全局,如果没有设置它。

动作钩子get_header 真的不是您想要的钩子,因为该钩子允许使用特定的头模板文件代替默认的头模板文件。

如果你想重定向,Wordpress 提供了一个函数wp_redirect()。所以不需要使用header( Location: )

另外,你真的需要那个条件来检查它是否是一个页面吗?

你可以试试这样的:

add_action( 'init', 'control_access' );
function control_access() {

    global $post;


    if ( ! is_user_logged_in() ) {

        if ( get_post_meta($post->ID, 'redirect', true) ) {

            wp_redirect( get_post_meta($post->ID, 'redirect', true) );
            exit;

        }


    } else {

        if ( get_post_meta($post->ID, 'Shortlink', true) ) {

            wp_redirect( get_post_meta($post->ID, 'Shortlink', true) );
            exit;

        }
    }
}

【讨论】:

  • 非常感谢您帮助我!但这并没有真正起作用,它不会重定向到自定义字段上的 URL。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-30
  • 1970-01-01
  • 2015-01-21
  • 1970-01-01
  • 2023-03-04
  • 2017-11-25
相关资源
最近更新 更多