自定义批量操作处理程序未触发

时间:2018-09-02 作者:slotdp02

我对Wordpress和PHP非常陌生,正在尝试为自定义帖子向批量编辑列表添加自定义字段。我关注了以下博文,但我的handle_bulk_actions 回调未启动:https://make.wordpress.org/core/2016/10/04/custom-bulk-actions/

这是我的代码:

/**
 * Adds a new item into the Bulk Actions dropdown for custom products 
list.
 */
function register_my_bulk_actions( $bulk_actions ) {
    $bulk_actions[\'out_of_stock\'] = \'Mark as Out of Stock\';
    $bulk_actions[\'in_stock\'] = \'Mark as In Stock\';
    debug_to_console( \'Hello console\' );
    return $bulk_actions;
}
add_filter( \'bulk_actions-edit-custom_product\', \'register_my_bulk_actions\' );

/**
 * Handles the bulk action above.
 * NOT FIRING!!
 */
function my_bulk_action_handler( $redirect_to, $action, $post_ids ) {
    debug_to_console( \'Running handler\' );
    if ( $action !== \'out_of_stock\' || $action !== \'in_stock\') {
        return $redirect_to;
    }

    // let\'s remove query args first
    $redirect_to = remove_query_arg( array( \'out_of_stock_done\', \'in_stock_done\' ), $redirect );

    foreach ( $post_ids as $post_id ) {
        if ($action === \'out_of_stock \') {
            wp_update_post( array(
                \'ID\' => $post_id,
                \'in_stock\' => \'no\',
            ) );
            $redirect_to = add_query_arg( \'out_of_stock_done\', count( $post_ids ), $redirect_to );
        }
        if ($action === \'in_stock \') {
            wp_update_post( array(
                \'ID\' => $post_id,
                \'in_stock\' => \'yes\',
            ) );
            $redirect_to = add_query_arg( \'in_stock_done\', count( $post_ids ), $redirect_to );
        }
    }

    return $redirect_to;
}
add_filter( \'handle_bulk_actions-edit-custom_product\', \'my_bulk_action_handler\', 10, 3 );

/**


* Shows a notice in the admin once the bulk action is completed.
 */
function my_bulk_action_admin_notice() {
    debug_to_console( \'Running notifier\' );
    if ( ! empty( $_REQUEST[\'bulk_out_of_stock\'] ) ) {
        $success_oos = intval( $_REQUEST[\'bulk_out_of_stock\'] );

        printf(
            \'<div id="message" class="updated fade">\' .
            _n( \'%s product updated!\', \'%s products updated!\', $drafts_count, \'domain\' )
            . \'</div>\',
            $success_oos
        );
    }
}
add_action( \'admin_notices\', \'my_bulk_action_admin_notice\' );
谢谢!

1 个回复
最合适的回答,由SO网友:Arash Rabiee 整理而成

嗨,首先修复你的状况

如果($action!=“out\\u of\\u stock”| |$action!=“in\\u stock”){

此条件将始终运行,因为您的操作与“out\\u of\\u stock”或“in\\u stock”相反。因此,我认为如果你将条件从或改为,它就会起作用。

然后找出屏幕id是否是您要查找的,然后修改过滤器:要了解您的屏幕id是什么,请将其添加到插件或主题函数中。php,请记住稍后将其删除:

add_filter( \'wc_product_has_unique_sku\', \'__return_false\' );

add_action(\'init\', \'test_function\');
function test_function(){
    $value = get_current_screen();
    echo \'<pre>\';
    print_r($value);
    echo \'</pre>\';
}
然后,当您获得正确的屏幕id(例如screen\\u id)时,请按如下方式修改过滤器:

add_filter( \'bulk_actions-SCREEN_ID\', \'register_my_bulk_actions\' ); 

结束