因此,我正在为一个客户端开发一个网站,其中主页像一个页面滚动器一样构建,但我也需要单个主页之外的其他页面的功能。我为这些部分构建了一个自定义的帖子类型,并使用此代码在主页上显示它们。
<?php query_posts( array('post_type'=>'homepage', 'posts_per_page' => 1000, 'orderby' => 'menu_order', 'order' => 'ASC') ); ?>
<?php if(have_posts()): while(have_posts()): the_post(); ?>
<?php
global $post;
$slug = $post->post_name;
locate_template(
array(
"template-$slug.php",
'template-main.php'
), true
);
?>
<?php endwhile; endif; ?>
因此,正如你所看到的,这是自动提取内容,并使用基于post-stug的页面模板来显示它,然而,我需要允许我的客户端根据下拉列表中选择的页面模板显示内容,我已经使用此代码创建了一个显示页面模板的下拉UI。
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'] );
}
}
所以,我现在面临的问题是如何根据选择的页面模板在主页中显示所有自定义帖子。
非常感谢!J
Wordpress实际上只为页面类型的帖子使用_wp_page_template
元字段。如果要更改模板,可以使用过滤器single template
。我建议你在主题/插件中放置好你正在使用的注释。。。。
btw将cpt
更新为您的帖子类型
function load_cpt_template($single_template) {
global $post;
if ($post->post_type == 'cpt') {
$new_template = get_post_meta( $post->ID, '_wp_page_template', true );
// if a blank field or not valid do nothing, load default..
if( is_file($new_template) )
$single_template = $new_template;
}
return $single_template;
}
add_filter( 'single_template', 'load_cpt_template' );