在我的 WordPress 页面上,我创建了一个短代码函数,它从帖子的 URL 获取参数。因此,我创建了这个简单的函数并将以下代码添加到主题文件 function.php
:
function getParam($param) {
if ($param !== null && $param !== '') {
echo $param;
} else {
echo "Success";
}
}
add_shortcode('myFunc', 'getParam');
而且我知道我必须使用(在我的例子中)[myFunc param='']
将这个短代码添加到帖子和页面中.
通常,我会使用 <?php $_GET['param'] ?>
从 URL 中获取参数值, 但在这种情况下,我不知道如何将此 PHP 代码发送到短代码函数。
例如,我怀疑我可以写[myFunc param=$_GET['param']]
.
最佳答案
像这样的简码:
[myFunc funcparam="param"]
此处不需要,除非调用的参数随帖子而变化。
假设您有这个 URL:
http://example.com?param=thisparam
要使用上述短代码获取“param”的值,您在 functions.php 中的函数应如下所示:
function sc_getParam() {
// Get parameter(s) from the shortcode
extract( shortcode_atts( array(
"funcparam" => 'funcparam',
), $atts ) );
// Check whether the parameter is not empty AND if there is
// something in the $_GET[]
if ( $funcparam != '' && isset( $_GET[ $funcparam ] ) ) {
// Sanitizing - this is for protection!
$thisparam = sanitize_text_field( $_GET[ $funcparam ] );
// Returning the value from the $_GET[], sanitized!
return $thisparam;
}
else {
// Something is not OK with the shortcode function, so it
// returns false
return false;
}
}
add_shortcode( 'myFunc', 'sc_getParam' );
查找这些引用资料:
WordPress Shortcodes: A Complete Guide - 创建短代码的教程
Validating Sanitizing and Escaping User Data - sanitizer
关于php - 添加发送参数的 WordPress 简码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39724530/