WP初心者です。どなたかご教示願えれば幸いです。
※kei344様、ご指摘いただきありがとうございます!内容を編集いたしました。
カスタムフィールドに入力した値の平均値を表示したいのですが、そういったことは可能でしょうか?
■やりたいこと
特定のカスタムフィールドに入力した値の、平均値を表示したい
※対象はカスタム投稿の全記事です。
■現状
カスタム投稿タイプ、カスタムフィールドは以下を参照にしています。
http://yahss.net/wordpress/587-custom_post_type_and_custom_field/
現状は、function.phpに以下のように記述しており、
<?php //----------------------------------------- // カスタム投稿タイプ //----------------------------------------- add_action( 'init', 'create_post_type' ); function create_post_type() { register_post_type( 'store', array( 'labels' => array( 'name' => __( 'ストア' ), 'singular_name' => __( 'ストア' ), 'all_items' => 'ストア一覧', ), 'public' => true, 'menu_position' =>5, 'has_archive' => true, 'supports' => array('title','editor','thumbnail') ) ); register_taxonomy( 'store-area', 'store', array( 'hierarchical' => true, 'update_count_callback' => '_update_post_term_count', 'label' => 'エリア', 'singular_label' => 'エリア', 'public' => true, 'show_ui' => true ) ); flush_rewrite_rules( true ); } //----------------------------------------- // カスタムフィールド //----------------------------------------- $meta_arr['price'] = array('価格','single'); /*** カスタムフィールドコンテンツの作り込み ***/ function my_meta_boxes() { global $post, $meta_arr; //metaの現在の登録値を取得(可変変数) foreach($meta_arr as $meta => $meta_val) { $true = ( $meta_val[1] == 'single' )? true: false; $val = $meta.'Val'; $nam = $meta.'Nam'; $$nam = $meta_val[0]; $$val = get_post_meta( $post->ID, $meta, $true ); } ?> <!--価格--> <p> <?php echo $priceNam ?><br> <input name="price" type="text" value="<?php echo $priceVal ?>" style="width:100%"> </p> <?php } /*** 投稿画面にカスタムフィールドのセクションを追加 ***/ function create_meta_box() { if ( function_exists('add_meta_box') ) add_meta_box( 'my-meta-boxes', 'ストア情報', 'my_meta_boxes', 'store', 'normal', 'high' ); } /*** カスタムフィールド入力値の保存 ***/ function save_postdata( $post_id ) { global $post, $meta_arr; foreach($meta_arr as $meta => $arr) { $true = ( $arr == 'single' )? true: false; $meta_cur = get_post_meta($post_id, $meta, $true); $meta_new = $_POST[$meta]; if( $meta_cur == "" && $meta_new != "") { add_post_meta($post_id, $meta, $meta_new, true); } elseif ( $meta_cur != $meta_new ) { update_post_meta($post_id, $meta, $meta_new); } elseif ( $meta_new == "" ) { delete_post_meta($post_id, $meta, get_post_meta($post_id, $meta_cur, true)); } } } add_action('admin_menu', 'create_meta_box'); add_action('save_post', 'save_postdata');
表示したい「~~~.php」のテンプレート上には、
$price = get_post_meta( $post->ID, 'price', true ); ?> <?php echo number_format($price); ?>
と、その値を表示しています。
例えば、カスタム投稿の記事を10個投稿したときに、記事1~記事10の「price」の値の平均値を表示したいのですが、
そういったことは可能なのでしょうか?
記述や方法など、ご教示願えたら幸いです。
お忙しい中恐れ入りますが、何卒よろしくお願いいたします。