Assign Wordpress Short code to PHP Variable?

有些话、适合烂在心里 提交于 2019-12-14 03:18:36

问题


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!


回答1:


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);



回答2:


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:


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.



来源:https://stackoverflow.com/questions/15287361/assign-wordpress-short-code-to-php-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!