是否使用模板选择器(页面UI)创建自定义Wordpress文章类型



我知道如何创建自定义帖子类型。从Codex中可以看出,我应该能够创建一个行为类似页面的自定义帖子类型,特别是使用模板选择器弹出窗口和类别/标记选择器分配模板的能力。

到目前为止,我得到的只是基本的编辑器,我可以得到一个特色的图像选择器。但我要找的基本上是一个页面,我可以把它当作一个自定义的帖子类型。

编辑:我以为这会很明显,但我是用函数来做的。hp:

register_post_type( hh_town,
array(
'labels' => array(
'name' => __( 'Towns' ),
'singular_name' => __( 'Town' ),
'add_new' => _x('Add Town', 'towns'),
'add_new_item' => __('Add Town'),
'edit' => _x('Edit Towns', 'Towns'),
'edit_item' => __('Edit Town'),
'new_item' => __('New Town'),
'view' => _x('View Town', 'towns'),
'view_item' => __('View Town')
),
'public' => true,
'has_archive' => true,
'hierarchical' => true,
'show_ui' => true,
'supports' => array('title','editor','page-attributes','thumbnail', 'custom-fields'),
'capability_type' => 'page',
'taxonomies' => array('post_tag','category')
)
);

旧线程,但万一有人遇到这个问题:您实际上不再需要任何自定义元框了。如果你创建了一个模板template-my-template.php并将其添加到顶部

<?php
/*
Template Name: My Template
Template Post Type: project, report, event
*/

然后,Template Post Type中列出的任何自定义帖子类型(也支持页面属性(add_post_type_support( 'my_post_type', ['page-attributes'] );))都将允许选择模板。

只需将此代码添加到您的函数中即可。php

add_action( 'add_meta_boxes', 'add_custom_page_attributes_meta_box' );
function add_custom_page_attributes_meta_box(){
global $post;
if ( 'page' != $post->post_type && post_type_supports($post->post_type, 'page-attributes') ) {
add_meta_box( 'custompageparentdiv', __('Template'), 'custom_page_attributes_meta_box', NULL, 'side', 'core');
}
}
function custom_page_attributes_meta_box($post) {
$template = get_post_meta( $post->ID, '_wp_page_template', 1 ); ?>
<select name="page_template" id="page_template">
<?php $default_title = apply_filters( 'default_page_template_title',  __( 'Default Template' ), 'meta-box' ); ?>
<option value="default"><?php echo esc_html( $default_title ); ?></option>
<?php page_template_dropdown($template); ?>
</select><?php
}
add_action( 'save_post', 'save_custom_page_attributes_meta_box' );
function save_custom_page_attributes_meta_box( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) return;
if ( ! current_user_can( 'edit_post', $post_id ) ) return;
if ( ! empty( $_POST['page_template'] ) && get_post_type( $post_id ) != 'page' ) {
update_post_meta( $post_id, '_wp_page_template', $_POST['page_template'] );
}
}

最新更新