問題描述
我已經設定了 CPT,以與帖子相同的方式進行操作,但用於釋出事件詳細資訊。
事實上,有些職位是未來的,而且這些職位是未來的日期。問題是普通使用者看不到這些帖子。
所以:
-
如何更改 archive-events.php 以列出未來的帖子?顯示遠期未來的帖子第一和最舊的帖子最後一次,同時保持分頁。
-
如何做到這一點,當使用者點選未來的帖子時,他們沒有找到 404 頁面,因為該帖子沒有在技術上釋出?
最佳解決方案
我已經能夠自己解決了。我註冊 CPT 的整個程式碼:
<?php
add_action( 'init', 'events_post_type_register' );
function events_post_type_register() {
$post_type = "events";
$labels = array(
'name' => _x('Events', 'post type general name', 'project_X'),
'singular_name' => _x('Event', 'post type singular name', 'project_X'),
'add_new' => _x('Add New', 'event', 'project_X'),
'add_new_item' => __('Add New Event', 'project_X'),
'edit_item' => __('Edit Event', 'project_X'),
'new_item' => __('New Event', 'project_X'),
'all_items' => __('All Events', 'project_X'),
'view_item' => __('View Event', 'project_X'),
'search_items' => __('Search Events', 'project_X'),
'not_found' => __('No events found', 'project_X'),
'not_found_in_trash' => __('No events found in trash', 'project_X'),
'parent_item_colon' => '',
'menu_name' => 'Events'
);
$args = array(
'labels' => $labels,
'public' => true,
'hierarchical' => false,
'has_archive' => true,
'rewrite' => array(
'with_front' => false,
'slug' => "news/{$post_type}"
),
'supports' => array( 'title', 'editor', 'thumbnail' )
);
register_post_type($post_type, $args);
remove_action("future_{$post_type}", '_future_post_hook');
add_action("future_{$post_type}", 'sc_ps_publish_future_events_now', 2, 10);
}
function sc_ps_publish_future_events_now($depreciated, $post) {
wp_publish_post($post);
}
add_filter('posts_where', 'sc_ps_show_future_events_where', 2, 10);
function sc_ps_show_future_events_where($where, $that) {
global $wpdb;
if("events" == $that->query_vars['post_type'] && is_archive())
$where = str_replace( "{$wpdb->posts}.post_status = 'publish'", "{$wpdb->posts}.post_status = 'publish' OR $wpdb->posts.post_status = 'future'", $where);
return $where;
}
?>
因此,即使將來您設定了所有使用者即使允許釋出資訊,您需要執行以下操作:
remove_action("future_{$post_type}", '_future_post_hook');
add_action("future_{$post_type}", 'sc_ps_publish_future_events_now', 2, 10);
我們刪除處理以後釋出的操作,並應用我們自己的操作強制其釋出,儘管它有以下日期:
wp_publish_post($post);
然後我們現在需要做的是透過過濾 posts_where 來顯示存檔頁面上的未來帖子:
function sc_ps_show_future_events_where($where, $that) {
global $wpdb;
if("events" == $that->query_vars['post_type'] && is_archive())
$where = str_replace( "{$wpdb->posts}.post_status = 'publish'", "{$wpdb->posts}.post_status = 'publish' OR $wpdb->posts.post_status = 'future'", $where);
return $where;
}
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。