运行时自定义元字段

时间:2016-04-04 04:46:48

标签: php wordpress custom-post-type custom-fields

我在自定义帖子类型中创建了一个元字段,以便从用户输入。现在我想如果管理面板中的用户想要通过按添加按钮创建另一个元字段,则创建另一个元字段。如果用户按下按钮很多次,则应创建许多元字段。我已经搜索了很多,以便在没有插件的情况下在运行时创建元字段,但是无法找到它。

代码

 function Print_price_fileds($cnt, $p = null) {
  if ($p === null){
   $a = $b = $c = '';
 }
 else{
   $a = $p['n'];
   $b = $p['d'];
   $c = $p['p'];
 }
return  <<<HTML
<li>
<label>Nr :</label>
<input type="text" name="price_data[$cnt][n]" size="10" value="$a"/>

<label>Description :</label>
<input type="text" name="price_data[$cnt][d]" size="50" value="$b"/>

<label>Price :</label>
<input type="text" name="price_data[$cnt][p]" size="20" value="$c"/>
<span class="remove">Remove</span>
 </li>
HTML
;
}


//add custom field - price
add_action("add_meta_boxes", "object_init");

function object_init(){
add_meta_box("price_meta_id", "Price fields :","price_meta", "services",   "normal", "low");

 }

 function price_meta(){
 global $post;
  $data = get_post_meta($post->ID,"services",true);
  //echo '<pre>'; var_dump($data); exit(0);
  echo '<div>';
 echo '<ul id="price_items">';
 $c = 0;
 if (count($data) > 0){
    foreach((array)$data as $p ){
        if (isset($p['p']) || isset($p['d'])|| isset($p['n'])){
            echo Print_price_fileds($c,$p);
            $c = $c +1;
        }
    }

 }
 echo '</ul>';

 ?>
    <span id="here"></span>
    <span class="add"><?php echo __('Add Price Data'); ?></span>
    <script>
        var $ =jQuery.noConflict();
            $(document).ready(function() {
            var count = <?php echo $c - 1; ?>; // substract 1 from $c
            $(".add").click(function() {
                count = count + 1;
                $('#price_items').append('<li><label>Nr :</label><input type="text" name="price_data[' + count + '][n]" size="10" value=""/><label>Description :</label><input type="text" name="price_data[' + count + '][d]" size="50" value=""/><label>Price :</label><input type="text" name="price_data[' + count + '][p]" size="20" value=""/><span class="remove">Remove</span></li>');
               $('#price_items').append('<? echo implode('',explode("\n",Print_price_fileds('count'))); ?>'.replace(/count/g, count));
                return false;
            });
            $(".remove").live('click', function() {
                $(this).parent().remove();
            });
        });
    </script>
    <style>#price_items {list-style: none;}</style>
  <?php
  echo '</div>';
  }


 //Save product price
 add_action('save_post', 'save_detailss');

 function save_detailss($post_id){ 
 global $post;


   // to prevent metadata or custom fields from disappearing... 
   if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
   return $post_id; 
  // OK, we're authenticated: we need to find and save the data
   if (isset($_POST['price_data'])){
    $data = $_POST['price_data'];
    update_post_meta($post_id,'price_data',$data);
}else{
    delete_post_meta($post_id,'price_data');
 }
}   

0 个答案:

没有答案