如何以函数(使用自定义写面板创建)的形式显示此元数据(数组)?

时间:2011-04-10 作者:janoChen

我使用以下代码创建自定义写入面板:

<?php

$key = "project";
$meta_boxes = array(
    "project_services" => array(
        "name" => "project_services",
        "title" => "Services",
        "description" => "List the services provided for the project."),
    "project_name" => array(
        "name" => "project_name",
        "title" => "Name",
        "description" => "Write the name of the project."),
    "project_overview" => array(
        "name" => "project_overview",
        "title" => "Overview",
        "description" => "Write an overview of the project.")
    );

function create_meta_box() {
    global $key;

    if( function_exists( \'add_meta_box\' ) ) {
        add_meta_box( \'new-meta-boxes\', ucfirst( $key ) . \' Description\', \'display_meta_box\', \'post\', \'normal\', \'high\' );
    }
}

function display_meta_box() {
    global $post, $meta_boxes, $key;
?>

<div class="form-wrap">

<?php
    wp_nonce_field( plugin_basename( __FILE__ ), $key . \'_wpnonce\', false, true );

    foreach($meta_boxes as $meta_box) {
        $data = get_post_meta($post->ID, $key, true);
?>

<div class="form-field form-required">
<label for="<?php echo $meta_box[ \'name\' ]; ?>"><?php echo $meta_box[ \'title\' ]; ?></label>
<input type="text" name="<?php echo $meta_box[ \'name\' ]; ?>" value="<?php echo htmlspecialchars( $data[ $meta_box[ \'name\' ] ] ); ?>" />
<p><?php echo $meta_box[ \'description\' ]; ?></p>
</div>

<?php } ?>

</div>
<?php
}

function save_meta_box( $post_id ) {
    global $post, $meta_boxes, $key;

    foreach( $meta_boxes as $meta_box ) {
        $data[ $meta_box[ \'name\' ] ] = $_POST[ $meta_box[ \'name\' ] ];
    }

    if ( !wp_verify_nonce( $_POST[ $key . \'_wpnonce\' ], plugin_basename(__FILE__) ) )
        return $post_id;

    if ( !current_user_can( \'edit_post\', $post_id ))
        return $post_id;

    update_post_meta( $post_id, $key, $data );
}
现在,我可以用以下方式调用该元数据:

<?php $data = get_post_meta( $post->ID, \'project\', true ); ?>
<p><?php echo $data[ \'project_services\' ]; ?></p>
但我想这样称呼它:

<p><?php project_services(); ?></p>
有什么建议吗?

1 个回复
最合适的回答,由SO网友:Chip Bennett 整理而成

试试这个?

<?php        
function get_project_services() {    
         global $post;
         $data = get_post_meta( $post->ID, \'project\', true );
         $project_services = $data[\'project_services\'];    
         return $project_services;    
}
?>
然后在模板文件中:

<p><?php echo get_project_services(); ?></p>
我想这能满足你的要求吗?

(根据您的评论进行编辑。)

结束

相关推荐

获取在Functions.php中设置的变量,并在我的Custom Post模板中回显它们

在我的函数中设置了以下函数。php文件,以允许我的自定义帖子类型“Slideshow”工作。add_action( \'the_post\', \'paginate_slide\' ); function paginate_slide( $post ) { global $pages, $multipage, $numpages; if( is_single() && get_post_type() == \'lom_s