从WordPress中的URL中提取参数

Chu*_*uck 23 php wordpress

我试图使用URL将参数传递给WordPress网站 - 例如:

www.fioriapts.com/?ppc=1 将是URL.

我打算在functions.php文件中编写一个函数,但是如何在WordPress中提取参数的机制超出了我的范围.我找到了很多关于如何使用函数向URL添加参数add_query_arg()但没有找到如何提取参数的示例.在此先感谢您的帮助.

Gra*_*bot 44

通过URL传递参数时,您可以将值检索为GET参数.

用这个:

$variable = $_GET['param_name'];

//Or as you have it
$ppc = $_GET['ppc'];
Run Code Online (Sandbox Code Playgroud)

首先检查变量更安全:

if (isset($_GET['ppc'])) {
  $ppc = $_GET['ppc'];
} else {
  //Handle the case where there is no parameter
}
Run Code Online (Sandbox Code Playgroud)

这里有一些关于你应该看的GET/POST参数的阅读:http://php.net/manual/en/reserved.variables.get.php

编辑:我看到这个答案在制作完成后仍然会有很多流量.阅读本答案附带的评论,特别是来自@emc的输入,其中详细说明了安全地实现此目标的WordPress功能.

  • `$ _GET`的替代方法是`$ _REQUEST`,但是_please_用于安全的使用[get_query_var](https://codex.wordpress.org/Function_Reference/get_query_var),如果可能的话.懒惰地解析原始URL参数是注入攻击的发生方式! (7认同)
  • 此方法是解决“get_query_var”和静态主页的愚蠢错误/功能的唯一方法:https://core.trac.wordpress.org/ticket/25143 (3认同)
  • @emc `get_query_var` 不适用于自定义查询变量检查 https://developer.wordpress.org/reference/functions/get_query_var/#more-information (3认同)
  • 这是否与WordPress的[**`get_query_var` **](https://codex.wordpress.org/Function_Reference/get_query_var)冲突? (2认同)

Mar*_*arc 32

为什么不使用WordPress get_query_var()功能呢?链接到Codex

// Test if the query exists at the URL
if ( get_query_var('ppc') ) {

    // If so echo the value
    echo get_query_var('ppc');

}
Run Code Online (Sandbox Code Playgroud)

由于get_query_var只能访问WP_Query可用的查询参数,因此为了访问自定义查询var(如'ppc'),您还需要在插件中注册此查询变量,或者functions.php在初始化期间添加操作:

add_action('init','add_get_val');
function add_get_val() { 
    global $wp; 
    $wp->add_query_var('ppc'); 
}
Run Code Online (Sandbox Code Playgroud)

或者通过向query_vars过滤器添加一个钩子:

function add_query_vars_filter( $vars ){
  $vars[] = "ppc";
  return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的方法 - Wordpress不鼓励访问$ _GET和$ _POST (8认同)
  • 另请注意:过滤器必须添加到functions.php 文件中。 (2认同)
  • 如果您的首页不是博客,则此方法将破坏主页。https://core.trac.wordpress.org/ticket/25143 (2认同)