【问题标题】:If statement for True/False user field wont work如果 True/False 用户字段的语句不起作用
【发布时间】:2017-02-28 22:09:23
【问题描述】:

我创建了一个附加到我的用户的 ACF True/False 字段。这用作访问级别选项,因此如果选项为 True,他们将在菜单中看到一个链接,如果为 false,他们将看到一个后备链接。

下面是 iv 添加到我的 functions.php 的代码,其中 iv 创建了一个短代码:“customLink”,然后将其添加到我的菜单链接中。 以下是我到目前为止所拥有的,希望能展示我正在尝试做的事情。如果用户角色我们是‘my_custom_role’,则获取 ACF 值,如果为 true,则显示一个链接,如果为 false,则显示另一个链接。

add_shortcode('customLink', 'cm_link');
function cm_link($atts) {
$atts = shortcode_atts(array('title' => 'Custom Link', 'fallbackurl' => '#'), $atts, 'customLink');
$advcontent = get_field('acf_field', $current_user->ID);
        $user = wp_get_current_user();
        if (!empty($user->roles) && is_array($user->roles)) {
            foreach ( $user->roles as $role ) {
                if ($role=='my_custom_role') {
                    if ($advcontent == 'true') {
                        return "<a href='/my-link/'>".$atts['title']."</a>";
                    }
                    if ($advcontent == 'false') {
                        return "<a>".$atts['title']."</a>";
                    }
                }
            }
        }        
    }

我也尝试了以下方法,但没有运气:

add_shortcode('customLink', 'cm_link');
function cm_link($atts) {
$atts = shortcode_atts(array('title' => 'Custom Link', 'fallbackurl' => '#'), $atts, 'customLink');
$advcontent = $_POST['acf']['field_58061ec5608bd'];
if ($advcontent == 'true' ) {
    return "<a href='/my-link'>".$atts['title']."</a>";
} else {
    return "<a>".$atts['title']."</a>";
    }      
}

【问题讨论】:

  • print_r($_POST) 调试这个以及你在哪里定义这个$current_user?,建议你添加 php error_reporting() 和 chk 错误

标签: php if-statement advanced-custom-fields


【解决方案1】:

真/假字段不会返回这样的值。如果选中,它基本上返回一个非空值,因此 get_field 是您需要做的所有事情才能返回它是否被选中。如果它被选中,那么你就做

   if ($advcontent) {
             return "<a href='/my-link/'>".$atts['title']."</a>";
   }  else {
             return "<a>".$atts['title']."</a>";
   }

如果您想要示例中的真/假,则可以使用值设置为真或假的单选按钮。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-26
    • 2013-06-20
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多