Woocommerce:save_post 挂钩未被触发

Woocommerce: save_post hook is not being triggered

我有一个元框,我正在为 woocommerce 附带的产品 post 类型编码。我 运行 遇到了一个我无法通过的问题,因为 'save_post' 挂钩似乎根本不适用于产品。它适用于 posts,但由于我更改了我的代码以适用于产品,所以它什么都不做。我所使用的 save_post 函数目前完全没有任何作用。我已经向其中添加了各种代码,但这并不重要,脚本似乎并没有走那么远。我是不是遗漏了什么明显的东西?

编辑:顺便说一句,我添加了

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

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

但它 returns 完全没有。

<?php
/*
*   Represents the plugin's Meta Box
*
*   @since          0.0.1
*   @package        BBPlugin
*   @subpackage     BBPlugin
*   @author         Christopher Dando <captaindando@gmail.com>
*/

/*
*   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 <captaindando@gmail.com>
*/

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;
    }






}
?>

在 Wordpress 中,save_post 本身并不是一个目的地;这是一个有效执行的操作 'between' 页面:您点击 更新,Wordpress 将在返回到相应页面之前在幕后执行一系列操作(通常是post 您刚刚在编辑,并收到有关该保存状态的通知。

因此,您永远不会看到 echoprint_r 或 JS alertconsole.log 的结果,因为 save_post 不是t 一个 user-facing 动作。

如果您想查看您的 save_post 操作是否以这种方式执行,我建议您输入 die(),如下所示:

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

如果正确触发了 save_post 操作,那么您应该会在空白页面上看到 JS 警报。如果您想查看您的函数是否正在执行任何实际的 Wordpress-style 功能,我建议您使用一个简单的 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);
}

然后您可以检查数据库(或单击以查看 post 中的自定义字段)以查看是否已添加您的自定义元数据。

我还建议将您的 save_post 操作 特别地 附加到 WooCommerce 使用的 product post 类型:

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

这将在以后节省一些冗余检查。