【发布时间】:2019-11-28 23:35:45
【问题描述】:
我在 WordPress 主题 (wue-theme.app) 中实现了 Vue.js 单页应用程序,并希望通过单篇文章模板中的下一个/上一个链接浏览博客文章。但我很难从链接中删除私人帖子 - 没有可用的 WP_Query 选项。那么如何才能浏览只有“发布”状态的帖子呢?
【问题讨论】:
标签: wordpress vue.js single-page-application
我在 WordPress 主题 (wue-theme.app) 中实现了 Vue.js 单页应用程序,并希望通过单篇文章模板中的下一个/上一个链接浏览博客文章。但我很难从链接中删除私人帖子 - 没有可用的 WP_Query 选项。那么如何才能浏览只有“发布”状态的帖子呢?
【问题讨论】:
标签: wordpress vue.js single-page-application
不幸的是,我找不到任何记录在案的“官方”方法来做到这一点。所以我“破解”了一些默认的 SQL 查询,幸运的是你可以在其上应用过滤器,并从查询中删除了“私有”post_status。这是您必须放置在您的functions.php中的“post”帖子类型的完整自定义代码:
add_filter( 'rest_prepare_post', 'technomad_post_api_hook', 10, 3 );
function technomad_post_api_hook( $response ) {
if ( isset( $_REQUEST["slug"] ) ) {
add_filter( "get_next_post_where", function($query, $in_same_cat, $excluded_categories, $taxonomy, $post){
$query = str_replace("OR p.post_status = 'private'", "", $query);
return $query;
}, 100, 5 );
add_filter( "get_previous_post_where", function($query, $in_same_cat, $excluded_categories, $taxonomy, $post){
$query = str_replace("OR p.post_status = 'private'", "", $query);
return $query;
}, 100, 5 );
$next = get_adjacent_post( false, '', false );
$previous = get_adjacent_post( false, '', true );
if ( is_a( $next, 'WP_Post' ) ) {
$response->data['next'] = array(
"id" => $next->ID,
"slug" => $next->post_name,
"title" => $next->post_title,
);
} else {
$response->data['next'] = null;
}
if ( is_a( $previous, 'WP_Post' ) ) {
$response->data['previous'] = array(
"id" => $previous->ID,
"slug" => $previous->post_name,
"title" => $previous->post_title,
);
} else {
$response->data['previous'] = null;
}
}
}
您也可以只返回您自己的自定义查询,而不是 str_replace():
return $wpdb->prepare( "WHERE p.post_title > %s AND p.post_type = %s AND ( p.post_status = 'publish' )", $post->post_title, $post->post_type );
【讨论】: