星期三 , 22 1 月 2025

OOP创建meta box




<?php 
class MetaField {
  public function __construct() {
    add_action( 'add_meta_boxes', array($this,'metabox') );
    add_action( 'save_post', array($this,'save_post_meta') );

  }

  public function metabox() {
    add_meta_box( 'seo_options', 'Seo Options', array($this,'seo_options'), 'post', 'normal', 'high' );
    
  }
  public function seo_options($post) {
    wp_nonce_field( basename(__FILE__), 'custom_seo_option_nonce' );
    $seo_title = get_post_meta( $post->ID, 'seo_title',true );
    $seo_desc = get_post_meta($post->ID,'seo_desc',true);

     ?>
    <div class="post_meta_row">
      <label for="seo_title">Seo Title</label>
      <input type="text" name="seo_title" id="seo_title" class="widefat" value="<?php echo $seo_title ?>">
    </div>
    <div class="post_meta_row">
      <label for="seo_desc">Seo Desc</label>
      <input type="text" name="seo_desc" id="seo_desc" class="widefat" value="<?php echo $seo_desc ?>">
    </div>


    <?php 

  }


  public function save_post_meta($post_id) {
    global $post;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
      return $post_id;
      // code...
    }
    if (!isset($_POST['custom_seo_option_nonce'])) {
      return $post_id;
      // code...
    }
    
    if (!current_user_can( 'edit_post' )) {
      return $post_id;
      // code...
    }

    if (wp_verify_nonce( $_POST['custom_seo_option_nonce'], basename(__FILE__))) {
     $custom_meta_fields = array(
      'seo_title',
      'seo_desc',


     );

     foreach ($custom_meta_fields as $custom_meta_field) {
       
      if (isset($_POST[$custom_meta_field]) && !empty($_POST[$custom_meta_field])) {
        //use array_filter ??? 
        $custom_meta_field_data = $_POST[$custom_meta_field];

        //if $custom_meta_field_data is array

        if (is_array($custom_meta_field_data)) {
          $custom_meta_field_data = array_filter($custom_meta_field_data);

          if (!empty($custom_meta_field_data)) {
            update_post_meta( $post_id, $custom_meta_field,$custom_meta_field_data );
            // code...
          }
          // code...
        } else { //if $custom_meta_field_data is not array 
          if (!empty($custom_meta_field_data)) {
            update_post_meta($post_id,$custom_meta_field,htmlspecialchars(stripslashes( $custom_meta_field_data )));
            // code...
          } else {
            delete_post_meta($post_id,$custom_meta_field);
          }
        }
        // code...
      } else {
        delete_post_meta( $post_id, $custom_meta_field );
      }

     }
    }


  }


}

$metafield = new MetaField();