我正在尝试创建一个基本的附属系统插件,目前将执行以下操作:
如果存在,请在任何页面中读取$\\u GET URL参数(例如http://mysite.com/about/?affid=1234). 如果没有,请跳过以下两个步骤
将其保存在cookie中,重定向到干净的URL(http://mysite.com/about/)我的问题在于第一部分和最后一部分(读取参数并重定向)。我不这么认为
add_query_var 是正确的方法,因为我只想跟踪引用,而不是在查询中使用参数。有什么想法吗?
编辑:以下是我目前拥有的:
add_action( \'template_redirect\', \'test_redirect\' );
function test_redirect() {
global $wp;
$wp->add_query_var(\'aff_id\');
//cookie related stuff goes here
$current_url = add_query_arg( $wp->query_string, \'\', home_url( $wp->request ) );
//strip the URL parameter aff_id from $current_url???
wp_redirect( $current_url ); exit;
}
Edit: Working code, thanks to all of you and specifically @Max who helped a lot.
<?php add_action(\'init\', \'affiliate_redirect\');
function affiliate_redirect() {
$varname = \'aff_id\';
$weeks = \'4\';
if( isset($_GET[$varname]) && \'\' != $_GET[$varname] ) {
setcookie(\'wp_affiliate\', $_GET[$varname], time()+648000*$weeks, \'/\');
$pageURL = \'http\';
if ( isset( $_SERVER["HTTPS"] ) && strtolower( $_SERVER["HTTPS"] ) == "on" ) {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
$url = preg_replace(\'/([?&])\'.$varname.\'=[^&]+(&|$)/\',\'$1\',$pageURL);
$last = $url[strlen($url)-1];
if ($last == \'?\') {
$url = substr_replace($url ,"",-1);
}
wp_redirect($url);
exit;
}
} ?>
最合适的回答,由SO网友:Max Yudin 整理而成
虽然未经测试,但应能正常工作删除>
<?php
add_action(\'send_headers\', \'affiliate_redirect\');
function affiliate_redirect() {
// it\'s possible to use \'if( !empty( $_GET[\'affid\']) )\'
if( isset($_GET[\'affid\']) && \'\' != $_GET[\'affid\'] ) {
if( empty($_COOKIE[\'affid\']) )
setcookie(\'affid\', $_GET[\'affid\'], time()+2592000, \'/\');
header(\'Location: http://mysite.com/about/\');
exit;
}
}