我有一个基本的 WordPress 代码,可以将某人重定向到网站上创建的最后一个帖子类型,在本例中,是“案例”帖子类型:
<?php
/*
Template Name: Redirect
*/
$args = array(
'posts_per_page' => '1',
'post_type' => 'case'
);
$post = get_posts($args);
if($post){
$url = get_permalink($post[0]->ID);
wp_redirect( $url, 301 );
exit;
}
我正在尝试扩展此代码,因此我仅将人们重定向到他们自己创建的帖子,因此他们将被重定向到他们创建的最后一个帖子,并在 URL 末尾添加了 ?mode=edit 等参数,并且如果他们未登录,他们将被发送到预定义的错误页面,例如domain.com/error。
我对 PHP 有点陌生,我一生都无法弄清楚。任何意见或提示表示赞赏。
我的计划是将此代码插入到我们将用作重定向点的一个或多个页面中,以便代码将嵌入到 WordPress 页面中。
您只需稍微调整代码即可将“author”参数添加到您的
get_posts()
调用中,设置为当前用户的 ID(如果当前用户拥有 ID)。
<?php
/*
Template Name: Redirect
*/
$args = array(
'posts_per_page' => '1',
'post_type' => 'case'
);
global $current_user;
if( $current_user && isset( $current_user->ID ) ) $args[ 'author' ] = $current_user->ID;
$post = get_posts($args);
if($post){
$url = get_permalink($post[0]->ID);
wp_redirect( $url, 301 );
exit;
}