我正在尝试使用cookie构建最近查看的WP小部件。
我的代码如下:
function complete_cookie() {
$data = get_the_ID();
//$data = implode( ',' , get_the_ID() ); // not working
setcookie( 'mp_last_viewed_cookie', json_encode( $data ), strtotime( '+30 days' ), COOKIEPATH, COOKIE_DOMAIN, false, false );
}
add_action( 'get_header', 'complete_cookie' );
在我的小部件中,我使用这样的cookie:
if ( $sortby == 'recently_viewed' ) {
if ( isset( $_COOKIE['mp_last_viewed_cookie'] ) ) {
$items = json_decode( stripslashes( $_COOKIE['mp_last_viewed_cookie'] ), true );
if ( ! empty( $items ) ) {
$params['post__in'] = array($items);
$params['orderby'] = 'post__in';
$params['post__not_in'] = array($post_id);
}
} else {
}
}
当我执行var_dump($items);
时,它只显示一个帖子ID,考虑到我使用$data = get_the_ID();
我尝试使用$data = implode( ',' , get_the_ID() );
,但这不起作用。任何人都想知道如何获得已查看的帖子ID列表,而不仅仅是一个?我想展示4个最新观看的帖子。
非常感谢任何帮助。
答案 0 :(得分:0)
如果json中的第一个元素是数组,那么json_decode将返回一个数组。 您不需要创建另一个数组,只需要将返回值赋给变量。
$params['post__in'] = $items;
将新ID附加到现有ID
if ( isset( $_COOKIE['mp_last_viewed_cookie'] ) ) {
$data = json_decode( stripslashes( $_COOKIE['mp_last_viewed_cookie'] ), true );
$data[] = get_the_ID();
} else {
$data = array(get_the_ID());
}
setcookie( 'mp_last_viewed_cookie', json_encode( $data ), strtotime( '+30 days' ), COOKIEPATH, COOKIE_DOMAIN, false, false );
答案 1 :(得分:0)
花了一些时间,但我终于开始工作了。
function complete_cookie() {
$viewed_posts = array();
if(isset($_COOKIE['mp_recently_viewed']) && $_COOKIE['mp_recently_viewed']!='') {
$viewed_posts = unserialize($_COOKIE['mp_recently_viewed']);
if (! is_array($viewed_posts)) {
$viewed_posts = array(get_the_ID());
} else{
$viewed_posts = array_diff($viewed_posts, array(get_the_ID())); // for removing current post in cookie
array_unshift($viewed_posts,get_the_ID());// update cookie with current post
}
} else {
$viewed_posts = array(get_the_ID());
}
setcookie( 'mp_recently_viewed', serialize($viewed_posts), strtotime( '+7 days' ), COOKIEPATH, COOKIE_DOMAIN, false, false );
}
add_action( 'get_header', 'complete_cookie' );
在小部件中我使用了这个:
$params = array(
'post_type' => 'download',
'posts_per_page' => $limit,
'post_status' => 'publish',
'offset' => $offset,
);
if ( $sortby == 'recently_viewed' ) {
if(isset($_COOKIE['mp_recently_viewed']) && $_COOKIE['mp_recently_viewed']!='') {
$viewed_posts = unserialize($_COOKIE['mp_recently_viewed']);
if ( ! empty( $viewed_posts ) ) {
$params['post__in'] = $viewed_posts;
$params['orderby'] = 'post__in';
$params['post__not_in'] = array( get_the_ID() );
}
} else {
}
}
$post_query = new WP_Query($params);