2016-01-27 2 views
0

У меня есть мета-ящик. Я кодирую тип сообщения продукта, который поставляется с woocommerce. Я столкнулся с проблемой, с которой я не могу согласиться, поскольку «save_post» не работает вообще с продуктами. Он отлично работает для сообщений, но поскольку я изменил свой код для работы с продуктами, он ничего не делает. Функция save_post, к которой я привязалась, ничего не делает на данный момент. Я добавил к нему всевозможные коды, и это не имеет значения, сценарий, похоже, не так далеко. я пропущу что-то очевидное?Woocommerce: save_post hook не запускается

Edit: как в сторону, я добавил

?> <script type="text/javascript"> 

      var post_id = '<?php $post_id ?>'; 
      console.log("id is: " + post_id); 
      </script><?php 

Но он не возвращает абсолютно ничего.

<?php 
/* 
* Represents the plugin's Meta Box 
* 
* @since   0.0.1 
* @package  BBPlugin 
* @subpackage  BBPlugin 
* @author   Christopher Dando <[email protected]> 
*/ 

/* 
* Represents the plugin's Meta Box 
* 
* Register's the meta box with the WordPress API, sets its properties, 
* by including the markup from its associated view 
* 
* @package  BBPlugin 
* @subpackage  BBPlugin/admin 
* @author   Christopher Dando <[email protected]> 
*/ 

class BBPlugin_Meta_Box{ 

    /* 
    * Register this class with the wordpress API 
    * 
    * @since 0.0.1 
    */ 
    public function initialize_hooks(){ 
     //add_action('add_meta_boxes_product', array($this, 'add_meta_box')); 
     add_action('add_meta_boxes', array($this, 'BBadd_meta_box')); 

     // This checks when wordpress is saving or 
     // updating a post. 
     add_action('save_post', array($this, 'save_post')); 
     $junk = $post_id; 
     ?> <script type="text/javascript"> 

      var post_id = '<?php global $post; echo $post->ID; ?>'; 
      console.log("id is: " + post_id); 
      </script><?php 
    } 


    // add_meta_boxes is the wordpress function. add_meta_box is our new function 

    /* 
    * The function responsible for creating the actual meta box. 
    * 
    * @since 0.0.1 
    */ 
    public function BBadd_meta_box(){ 
     ?> <script>console.log("meta box added");</script><?php 
     add_meta_box(
      'BBPlugin', 
      "Brave Books", 
      array($this, 'display_meta_box'), 
      'product', 
      'normal', 
      'default' 
     ); 
    } 
    // This defines the properties of the meta box. 

    /* 
    * Renders the content of the meta box. 
    * 
    * @since 0.0.1 
    */ 
    public function display_meta_box(){ 
     include_once('views/BBPlugin-navigation.php'); 
    } 


    /** 
    * Sanitizes and serializes the information associated with this post. 
    * 
    * @since 0.0.1 
    * 
    * @param int $post_id The ID of the post that's currently being edited. 
    */ 

    // strangely, this calls if the meta box does not render 
    public function save_post($post_id) { 
     ?><script>alert("post saved");</script><?php 
     /* If we're not working with a 'product' post type or the 
      user doesn't have permission to save, 
      then we exit the function. 
     */ 
     if (! $this->user_can_save($post_id, 'BBPlugin_nonce', 'BBPlugin_save')) { 

      return; 
     } 

     /* 
      We need to 'Sanitise' our information before 
      we can save it to the database. What this means 
      is that we must strip it of html tags 
      and extract the text itself. 
     */ 

     // If the 'Resources' inputs exist, iterate through them and sanitize them 
     if ($this->value_exists('BBPlugin-resources')) { 
      // This is all divs with the id of meta-box-resources 
      $this->update_post_meta(
       $post_id, 
       'BBPlugin-resources', 
       $this->sanitize_data('BBPlugin-resources', true) 
      ); 
     } 
     else { 
      // leaving an input blank on the front end will remove that specific input. 
      $this->delete_post_meta($post_id, 'BBPlugin-resources'); 
     } 

    } 



    /** 
    * Determines whether or not a value exists in the $_POST collection 
    * identified by the specified key. 
    * 
    * @since 0.0.1 
    * 
    * @param string $key The key of the value in the $_POST collection. 
    * @return bool    True if the value exists; otherwise, false. 
    */ 
    private function value_exists($key) { 
     return ! empty($_POST[ $key ]); 
    } 

    /** 
    * Deletes the specified meta data associated with the specified post ID 
    * based on the incoming key. 
    * 
    * @since 0.0.1 
    * @access private 
    * @param int $post_id The ID of the post containing the meta data 
    * @param string $meta_key The ID of the meta data value 
    */ 
    private function delete_post_meta($post_id, $meta_key) { 
     if ('' !== get_post_meta($post_id, $meta_key, true)) { 
      delete_post_meta($post_id, '$meta_key'); 
     } 
    } 

    private function update_post_meta($post_id, $meta_key, $meta_value) { 
     if (is_array($_POST[ $meta_key ])) { 
      $meta_value = array_filter($_POST[ $meta_key ]); 
     } 
     /* 
      Update_post_meta also adds to a database if there is nothing there already. 
      parameters are as follows: 

      1. The post ID used to associate this information with the post. 
      2. A meta key that's used to uniquely identify the value. 
      3. The actual value associated with the meta key. 
     */ 
     update_post_meta($post_id, $meta_key, $meta_value); 
    } 

    /** 
    * Sanitizes the data in the $_POST collection identified by the specified key 
    * based on whether or not the data is text or is an array. 
    * 
    * @since 1.0.0 
    * @access private 
    * @param string  $key      The key used to retrieve the data from the $_POST collection. 
    * @param bool   $is_array Optional. True if the incoming data is an array. 
    * @return array|string       The sanitized data. 
    */ 
    private function sanitize_data($key, $is_array = false) { 
     $sanitized_data = null; 
     if ($is_array) { 
      $resources = $_POST[ $key ]; 
      $sanitized_data = array(); 
      foreach ($resources as $resource) { 
       $resource = esc_url(strip_tags($resource)); 
       if (! empty($resource)) { 
        $sanitized_data[] = $resource; 
       } 
      } 
     } 
     else { 
      $sanitized_data = ''; 
      $sanitized_data = trim($_POST[ $key ]); 
      $sanitized_data = esc_textarea(strip_tags($sanitized_data)); 
     } 
     return $sanitized_data; 
    } 

    /** 
    * Verifies that the post type that's being saved is actually a post (versus a page or another 
    * custom post type. 
    * 
    * 
    * @since  0.0.1 
    * @access  private 
    * @return  bool  Return if the current post type is a post; false, otherwise. 
    */ 
    private function is_valid_post_type() { 
     return ! empty($_POST['post_type']) && 'post' == $_POST['post_type']; 
    } 

    /** 
    * Determines whether or not the current user has the ability to save meta data associated with this post. 
    * 
    * @since  0.0.1 
    * @access  private 
    * @param  int  $post_id  The ID of the post being save 
    * @param  string $nonce_action The name of the action associated with the nonce. 
    * @param  string $nonce_id  The ID of the nonce field. 
    * @return  bool     Whether or not the user has the ability to save this post. 
    */ 
    private function user_can_save($post_id, $nonce_action, $nonce_id) { 

     $is_autosave = wp_is_post_autosave($post_id); 
     $is_revision = wp_is_post_revision($post_id); 
     $is_valid_nonce = (isset($_POST[ $nonce_action ]) && wp_verify_nonce($_POST[ $nonce_action ], $nonce_id)); 

     // Return true if the user is able to save; otherwise, false. 
     return ! ($is_autosave || $is_revision) && $this->is_valid_post_type() && $is_valid_nonce; 
    } 






} 
?> 

ответ

1

В Wordpress save_post не является самоцелью; это действие эффективно выполняется между страницами: вы нажмете Update, а Wordpress выполнит ряд действий за кулисами, прежде чем возвращать вас на соответствующую страницу (неизменно сообщение, которое вы только что редактировали, с уведомлением о статус этого сохранения).

Таким образом, вы никогда не будете видеть результаты в echo, print_r или JS alert или console.log, потому что save_post не является пользователем обращенных действий.

Если вы хотите увидеть, если ваш save_post действие осуществляется таким образом, я бы рекомендовал бросать в die(), например, так:

public function save_post($post_id) { 
    ?><script>alert("post saved");</script><?php 
    die(); 
} 

Если save_post действие увольняют правильно, то вам должен видеть предупреждение JS на пустой странице. Если вы хотите увидеть, если ваша функция проведения какой-либо фактической функциональности Wordpress стиля, я бы рекомендовал простой update_post_meta подтвердить:

public function save_post($post_id) { 
    // Insert some actual logic to ensure you're not doing this on every post all the time 

    update_post_meta($post_id, 'i_am_saved', 'totes saved to post #' . $post_id); 
} 

Вы можете проверить базу данных (или нажмите для просмотра пользовательских полей в пределах этот пост), чтобы узнать, добавлены ли ваши пользовательские метаданные.

Я хотел бы также рекомендовать прикрепление своего save_post действия специально к типу product сообщению, который используется WooCommerce:

add_action('save_post_product', array($this, 'save_post'));

Это сэкономит проверки некоторой избыточности позже.

+0

Огромное вам спасибо, я часами пытаюсь разбить мой мозг, пытаясь заставить его работать –

+0

Нет проблем - рад, что вы его работали. – indextwo

+0

кажется, что если я использую функцию wp_is_post_revision ($ post_id) ;, она всегда возвращается как ложная. это связано с той же проблемой? –

Смежные вопросы