php - 添加发送参数的 WordPress 简码

标签 php wordpress

在我的 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' );

查找这些引用资料:

关于php - 添加发送参数的 WordPress 简码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39724530/

相关文章:

php - 如何使用 PHP 设置 WebSocket 安全连接?

php - 抓取标题、描述和关键字的可靠方法

PHP 字符串转时间格式

javascript - jQuery 或 Javascript 客户端图像在上传前调整大小

php - WooCommerce - 基于子类别的条件购物车计算

php - 由于地理邻近度公式(商店定位器)而缺少结果

php - 标题 WordPress 中的登录/注册和货币小部件

php - 在php中递归地提取数据库信息

mysql - WordPress WP-Dbmanager 0/1 查询已成功执行

重新加载页面时无法识别 CSS 文件修订版