プラグインWooCommerceのwoocommerce_trash_cancelled_orders_query_argsフィルタの使用方法・解説

概要

woocommerce_trash_cancelled_orders_query_args フィルタは、WooCommerceプラグインにおいてキャンセルされた注文をゴミ箱へ移動する際のクエリ引数を変更するために使用されます。このフックを使用することで、特定の条件に基づいてキャンセルされた注文の取り扱いをカスタマイズすることができます。特に以下のような機能を実装する際によく使われます。

  1. キャンセル注文の保存期間の変更
  2. 特定の注文ステータスを自動的にゴミ箱に移動
  3. ユーザー役割に基づく注文のフィルタリング
  4. 日付やタイムスタンプに基づく条件の追加
  5. 他のプラグインとの互換性を保持するためのカスタマイズ
  6. 移動する注文のカスタムメタデータに基づくフィルタリング

構文

add_filter( 'woocommerce_trash_cancelled_orders_query_args', 'custom_function' );
function custom_function( $query_args ) {
    // カスタマイズを行うコード
    return $query_args;
}

パラメータ

  • $query_args: キャンセルされた注文をゴミ箱へ移動するためのクエリ引数を含む配列。

戻り値

  • 変更された、または未変更のクエリ引数を含む配列。

プラグインおよびバージョン

  • このフィルタはWooCommerceプラグインで使用可能で、WordPressのバージョン4.0以上で動作します。WooCommerceの対応バージョンは3.0以上です。

この関数のアクションでの使用可能性

アクション 使用例
mu_plugin_loaded
registered_post_type
plugins_loaded
wp_roles_init
setup_theme
after_setup_theme
set_current_user
init
register_sidebar
wp_loaded
send_headers
parse_query
pre_get_posts
wp
template_redirect
get_header
wp_head

サンプルコード

サンプルコード1

add_filter( 'woocommerce_trash_cancelled_orders_query_args', 'custom_trash_order_args' );
function custom_trash_order_args( $query_args ) {
    $query_args['date_query'] = array(
        array(
            'before' => '30 days ago',
        ),
    );
    return $query_args;
}

このコードは、30日前よりも前にキャンセルされた注文のみをゴミ箱に移動します。

サンプルコード2

add_filter( 'woocommerce_trash_cancelled_orders_query_args', 'modify_cancelled_orders' );
function modify_cancelled_orders( $query_args ) {
    $query_args['meta_query'] = array(
        array(
            'key'     => '_custom_meta_key',
            'value'   => '1',
            'compare' => '='
        )
    );
    return $query_args;
}

このコードは、カスタムメタデータが特定の値を持つキャンセル注文のみをゴミ箱に移動させます。

サンプルコード3

add_filter( 'woocommerce_trash_cancelled_orders_query_args', 'limit_cancelled_orders' );
function limit_cancelled_orders( $query_args ) {
    $query_args['posts_per_page'] = 50; // 最多50件をゴミ箱に移動
    return $query_args;
}

このコードは、キャンセルされた注文を最大50件までゴミ箱に移動します。

サンプルコード4

add_filter( 'woocommerce_trash_cancelled_orders_query_args', 'custom_user_role_trash' );
function custom_user_role_trash( $query_args ) {
    if ( current_user_can('administrator') ) {
        $query_args['author'] = get_current_user_id(); // 現在のユーザーによって作成されたキャンセル注文のみをゴミ箱に
    }
    return $query_args;
}

このコードは、管理者権限を持つユーザーによって作成されたキャンセル注文のみをゴミ箱に移動する設定です。

サンプルコード5

add_filter( 'woocommerce_trash_cancelled_orders_query_args', 'exclude_specific_orders' );
function exclude_specific_orders( $query_args ) {
    $query_args['post__not_in'] = array( 123, 456 ); // 特定の注文IDを除外
    return $query_args;
}

このコードは、特定の注文ID(123と456)をゴミ箱に移動しないようにします。

このフィルタの詳細な情報は、WooCommerceの公式ドキュメント等をご参照ください。

この関数について質問する


上の計算式の答えを入力してください