我目前使用 WordPress 5.6.2 并正在开发插件。
我需要为自定义帖子类型设置自定义模板。
我的自定义帖子类型是 reseller_r_limit
。
当我点击 Add new
按钮时,当前页面看起来像 http://localhost/project/wp-admin/post-new.php?post_type=reseller_r_limit
。
我参考了很多类似的问题,我知道我们需要使用 single-{post_type}.php
。我这样做了,我的插件文件夹层次结构如下所示:
reseller program
--> reseller_program.php
--> templates
--> single-reseller_r_limit.php
single-reseller_r_limit.php
下的内容如下所示,带有简单的回显消息:
<?php
echo "Hey";
我使用 post_type
注册了 register_post_type
,如下所示:
add_action('init','reseller_limit_post_type');
function reseller_limit_post_type(){
register_post_type('reseller_r_limit',
array(
'labels' => array(
'name' => __('Reseller Redeem Limits'),
'singular_name' => __('Reseller Redeem Limits'),
),
'public' => false,
'has_archive' => true,
'show_ui' => true,
'show_in_nav_menus' => false,
'show_in_admin_bar' => true,
'publicly_queryable' => false,
'exclude_from_search' => true,
'hierarchical' => true,
'rewrite' => false,
'query_var' => false,
)
);
}
问题是当我点击 add new
按钮时我仍然看不到 嘿,这意味着 Wordpress 仍然无法找到模板文件,它直接带我添加一个新的常规职位。谁能告诉我我哪里出错了?
答案 0 :(得分:0)
正如 @CBroe
在评论中提到的,single-{post_type}.php
文件仅用于前端模板。
如果您想在管理面板里面将自定义元字段添加到您的自定义帖子类型,您需要执行以下操作:
使用 add_meta_boxes
钩子添加您的自定义字段,如下所示:
<?php
add_action( 'add_meta_boxes', 'reseller_meta_boxes',10,2);
function reseller_meta_boxes($post_type, $post){
if($post_type == "reseller_r_limit"){
add_meta_box( 'reseller-limit-country', 'Reseller Country', 'reseller_limit_country_field' );
// all other fields
}
}
function reseller_limit_country_field( $post ){
$reseller_country = get_post_meta($post->ID,'reseller_country',true);
$countries_obj = new WC_Countries();
$countries = $countries_obj->__get('countries');
echo '<label for="reseller_country">Reseller Country:</label>';
woocommerce_form_field('reseller_country', array(
'type' => 'select',
'class' => array( 'chzn-drop' ),
'placeholder' => __('Enter something'),
'options' => $countries,
'default' => empty($reseller_country) ? 'GB' : $reseller_country
)
);
}
要覆盖通常的帖子字段,您可以在 supports
方法中使用 register_post_type
键的值。如果您不想要由
wordpress,你可以简单地在一个数组中传递一个空值,如下所示:
register_post_type('reseller_r_limit',
array(
'labels' => array(
'name' => __('Reseller Redeem Limits'),
'singular_name' => __('Reseller Redeem Limits'),
'add_new_item' => 'Add new limit'
),
'public' => false,
'has_archive' => true,
'show_ui' => true,
'show_in_nav_menus' => false,
'show_in_admin_bar' => true,
'publicly_queryable' => false,
'exclude_from_search' => true,
'hierarchical' => false,
'rewrite' => false,
'query_var' => false,
'supports' => array('') // here, or if you want some, you can have like array('title','editor','author','excerpt') etc
)
);