Woocommerce:没有触发save_post挂钩

时间:2016-01-27 14:15:19

标签: php wordpress woocommerce meta-boxes

我有一个元框,我编写了与woocommerce一起提供的产品发布类型。我遇到了一个问题,我无法通过' save_post'钩子似乎根本不适用于产品。它适用于帖子,但由于我已将我的代码更改为适用于产品,因此它无效。我挂钩的save_post功能目前绝对没有任何功能。我已经为它添加了各种代码并且它并不重要,脚本似乎没有达到那么远。我错过了一些明显的东西吗?

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

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






}
?>

1 个答案:

答案 0 :(得分:1)

在Wordpress中,save_post本身不是目的地;这是一个在页面之间有效执行的操作:您点击更新,Wordpress将在幕后执行一系列操作,然后返回相应的页面(总是您刚刚编辑的帖子) ,并提供有关该保存状态的通知。)

因此,您永远不会看到echoprint_r或JS alertconsole.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操作专门附加到WooCommerce使用的product帖子类型:

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

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