Assign Wordpress Short code to PHP Variable?

2019-08-28 02:41发布

I'm trying to compare a email address held in a PHP variable with a email address held in a short code in Wordpress, this is what I've tried so far:

$email = 'someone@something.com';
$user_email = do_shortcode('[userinfo field="user_email"]');
echo var_dump(strcmp($user_email, $email) === 0);

But the var_dump always returns false, I'm positive they are the exact same string!

3条回答
再贱就再见
2楼-- · 2019-08-28 03:10

You should not use the shortcode for that but just the Wordpress API function to obtain the current users email address:

$email = 'someone@something.com';

global $user_email;
get_currentuserinfo();

echo var_dump(strcmp($user_email, $email) === 0);

The Worpdress API function get_currentuserinfo() sets the global variable $user_email to the email address of the current user as a string.

查看更多
疯言疯语
3楼-- · 2019-08-28 03:11

See if there are any spaces and if any of the string needs to be trimmed, because if both the strings are same then your code seems to work already.

$email = 'someone@something.com';
$user_email = 'someone@something.com';
$var = (string) $user_email; // Casts to string
$var2 = (string) $email; // Casts to string
echo var_dump(strcmp($var, $var2) === 0);

Returns bool(true)

Probably do_shortcode('[userinfo field="user_email"]'); needs to be trimmed. Also you can simply echo $user_email before comparison to see if there is any unexpected value there.

查看更多
我只想做你的唯一
4楼-- · 2019-08-28 03:16

By default the userinfo shortcode returns the data wrapped in a <span> tag. To suppress the span tag you can use the nospan-attribute.

The description of the plugin says the following:

[userinfo nospan="true"] should eliminate the surrounding span tag so the output can be used inside URLs or similar applications

So your code should look like that:

$email = 'someone@something.com';
$user_email = do_shortcode('[userinfo field="user_email" nospan="true"]');
$var = (string) $user_email; // Casts to string
$var2 = (string) $email; // Casts to string
echo var_dump(strcmp($var, $var2) === 0);
查看更多
登录 后发表回答