Chu*_*k D 65 php url wordpress get
我在尝试将url中的额外变量传递给我的wordpress安装时遇到了麻烦.
例如 /news?c=123
出于某种原因,它仅适用于网站根目录,www.example.com?c=123但如果网址包含更多信息则不起作用www.example.com/news?c=123.我在theme目录中的functions.php文件中有以下代码.
if (isset($_GET['c']))
{
setcookie("cCookie", $_GET['c']);
}
if (isset($_SERVER['HTTP_REFERER']))
{
setcookie("rCookie", $_SERVER['HTTP_REFERER']);
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
Tom*_*ger 104
要在"前端"上进行往返"WordPress方式"(在上下文中不起作用wp-admin),您需要使用3个WordPress功能:
wp-admin-所以这也不会是可用admin-ajax)注意:$_GET如果你这样做的话,甚至不需要触摸superglobals().
在您需要创建链接的页面上/设置查询变量:
如果它是返回此页面的链接,只需添加查询变量即可
<a href="<?php echo esc_url( add_query_arg( 'c', $my_value_for_c ) )?>">
如果它是指向其他页面的链接
<a href="<?php echo esc_url( add_query_arg( 'c', $my_value_for_c, site_url( '/some_other_page/' ) ) )?>">
在您的functions.php或某些插件文件或自定义类(仅限前端)中:
function add_custom_query_var( $vars ){
$vars[] = "c";
return $vars;
}
add_filter( 'query_vars', 'add_custom_query_var' );
Run Code Online (Sandbox Code Playgroud)
在您要检索的页面/函数上,使用URL中的查询var set:
$my_c = get_query_var( 'c' );
wp-admin)在后端我们没有运行wp(),所以主要的WP查询不会运行.结果,没有query vars,并且query_vars钩子没有运行.
在这种情况下,您需要恢复检查$_GET超全局的更标准方法.最好的方法可能是:
$my_c = filter_input( INPUT_GET, "c", FILTER_SANITIZE_STRING );
虽然在紧要关头,你可以做到尝试和真实
$my_c = isset( $_GET['c'] ? $_GET['c'] : "";
或其某些变体.
sha*_*han 14
在function.php中添加以下代码
add_filter( 'query_vars', 'addnew_query_vars', 10, 1 );
function addnew_query_vars($vars)
{
$vars[] = 'var1'; // var1 is the name of variable you want to add
return $vars;
}
Run Code Online (Sandbox Code Playgroud)
然后你就可以使用$ _GET ['var1']
sha*_*ver 10
由于这是一个经常访问的帖子,我想发布我的解决方案,以防它帮助任何人.在WordPress中使用查询变量,您可以像这样更改永久链接
www.example.com?c=123 to www.example.com/c/123
Run Code Online (Sandbox Code Playgroud)
为此,您必须在functions.php或插件基本文件中添加这些代码行.
来自shankhan的 anwer
add_filter( 'query_vars', 'addnew_query_vars', 10, 1 );
function addnew_query_vars($vars)
{
$vars[] = 'c'; // c is the name of variable you want to add
return $vars;
}
Run Code Online (Sandbox Code Playgroud)
此外,这还剪切了添加自定义重写规则.
function custom_rewrite_basic()
{
add_rewrite_rule('^c/([0-9]+)/?', '?c=$1', 'top');
}
add_action('init', 'custom_rewrite_basic');
Run Code Online (Sandbox Code Playgroud)
对于需要为特定页面添加重写规则的情况,您可以使用该页面slug为该特定页面编写重写规则.就像OP提出的问题一样
www.example.com/news?c=123 to www.example.com/news/123
Run Code Online (Sandbox Code Playgroud)
我们可以通过对我们之前的函数添加一些修改来将其更改为所需的行为.
function custom_rewrite_basic()
{
add_rewrite_rule('^news/([0-9]+)/?', 'news?c=$1', 'top');
}
add_action('init', 'custom_rewrite_basic');
Run Code Online (Sandbox Code Playgroud)
希望它对某人有用.