在插件中调用自定义帖子类型

时间:2016-04-02 00:36:51

标签: wordpress plugins

我正在编写一个插件,其中我有以下自定义帖子类型:

function create_post_type_contact() {
register_post_type('contact', 
    array(
        'labels' => array(
            'name' => __( 'Contacts'),
                    'singular_name' => __( 'contact'),
            'add_new' => __('Add New contact' ),
            'add_new_item' => __('Add New contact' ),
            'edit_item' => 'Edit Contact',
            'new_item' => 'New Contact',
            'view_item' => 'View Contact',
            'search_items' => 'Search Contact',
            'not_found' => 'No contacts found',
            'not_found_in_trash' => 'No contacts found in Trash'
            ),
    'public' => true,
    'menu_position' => 24,
    'menu_icon' => 'dashicons-email',
    'rewrite' => array(
        'slug' => __('contact')
    ),
    'supports' => array( 'title'),
));
}

还添加了以下自定义元字段:

// Field Array  
$custom_meta_fields_contact = array(  
array(
    'label'=> __('Contact Name'),  
    'desc'  => 'Enter Contact Name here',  
    'id'    => 'contact_name',  
    'type'  => 'text'
),
array(
    'label'=> __('Contact Address'),  
    'desc'  => 'Enter Contact address here',  
    'id'    => 'contact_address',  
    'type'  => 'textarea'
),
array(
    'label'=> __('Contact No'),  
    'desc'  => 'Enter Contact number here',  
    'id'    => 'contact_no',  
    'type'  => 'text'
),
array(
    'label'=> __('Contact Email'),  
    'desc'  => 'enter contact email id here',  
    'id'    => 'contact_email',  
    'type'  => 'text'
),
);

我添加了显示自定义元字段和保存自定义元的功能,这样就可以了。

在这个插件中,我需要调用contact_email元字段。我为此添加了以下代码:

// get the Contact email address
$args_contact = array('post_type' => 'contact');

$contact_posts = new WP_Query($args_contact);
if($contact_posts->have_posts()) : 
    while($contact_posts->have_posts()) :   $contact_posts->the_post();
        $to = get_post_meta($post->ID, 'contact_email');
    endwhile;   endif;
wp_reset_query();

但每当我试图在插件中获取$的值时,它什么都不返回。在联系页面中我能够正确显示contact_name,contact_number,contact_address和contact_email。

任何帮助或建议都将不胜感激。

1 个答案:

答案 0 :(得分:0)

使用此

get_post_meta(get_the_ID(), 'contact_email', true);

如果条件

,则声明全局$ post变量
if($contact_posts->have_posts()) : 
global $post;