【发布时间】:2021-07-14 00:46:04
【问题描述】:
我创建了一个简码,我总是使用 URL 参数来动态交换主页上的特色产品,效果很好:
// Shortcode to display specific product page via URL - ?myppid=46
// =============================================================================
function ppid_from_query( $atts ) {
$atts = shortcode_atts( array(
'default' => 46
), $atts, 'myppid' );
$pp_id = $atts['default'];
if ( isset( $_REQUEST['ppid'] ) && $_REQUEST['ppid'] != '' ) {
$pp_id = intval( $_REQUEST['ppid'] );
}
return do_shortcode( "[product_page id='".$pp_id."']" );
}
add_shortcode( 'myppid', 'ppid_from_query' );
我面临的挑战是,如果用户转到我网站上的任何其他页面并返回,URL 参数就会消失,并且会显示默认产品。
我已经尝试了几种传递参数的方法,但都没有成功……即使我成功了,它也只适用于那个会话。换句话说,如果用户离开站点并在没有 ?ppid=X 的情况下返回主域,那么他们将看不到该产品。所以为此,我尝试为我找到的这个线程设置一个 cookie(当然它有点过时了):https://wordpress.stackexchange.com/questions/188749/i-am-looking-to-append-url-parameter-to-all-urls
所以在我的标题中,我有:
<script>
if(!isset($_SESSION['ppid']) and $_GET['ppid']){
$cookie_expire = time()+60*60*24*30;
$_SESSION['ppid'] = $_GET['ppid'];
setcookie('ppid', $_SESSION['ppid'], $cookie_expire, '/', '.'.$_SERVER['HTTP_HOST']);
</script>
在函数中:
function wprdcv_param_redirect(){
if(isset($_COOKIE['ppid']) and !$_GET['ppid']){
$location = esc_url(add_query_arg('ppid', $_COOKIE['ppid']));
wp_redirect($location);
}
}
add_action('template_redirect', 'wprdcv_param_redirect');
仍然没有运气。我做错了什么?
【问题讨论】:
标签: wordpress cookies woocommerce url-parameters