検索
ホームページバックエンド開発PHPチュートリアルWooCommerce 4 でカスタム在庫ステータスを作成して使用する方法

How to Create and Use Custom Stock Statuses in WooCommerce 4 ?

WooCommerce 4 で商品にカスタム在庫ステータスを追加する方法

背景

WooCommerceデフォルトでは、「在庫あり」、「在庫切れ」、「入荷待ち」など、いくつかの在庫ステータスが表示されます。ただし、特定の在庫管理ニーズに合わせてカスタム在庫ステータスを作成する必要がある場合があります。

カスタム在庫ステータスの作成

カスタム在庫ステータスを作成するには、次のコードを使用します。テーマの function.php ファイルまたはカスタム プラグインのスニペット:

<code class="php">use WooCommerce\Admin\HTML;
use WooCommerce\Utilities\Product;</code>
<code class="php">/**
 * Add custom stock status options.
 *
 * @param array $status Existing stock status options.
 * @return array Updated stock status options.
 */
function filter_woocommerce_product_stock_status_options( $status ) {
    // Add new statuses
    $status['pre_order'] = __( 'Pre order', 'woocommerce' );
    $status['contact_us'] = __( 'Contact us', 'woocommerce' );

    return $status;
}
add_filter( 'woocommerce_product_stock_status_options', 'filter_woocommerce_product_stock_status_options', 10, 1 );

/**
 * Modify availability text based on stock status.
 *
 * @param string $availability Availability text.
 * @param WC_Product $product Product object.
 * @return string Modified availability text.
 */
function filter_woocommerce_get_availability_text( $availability, $product ) {
    // Get stock status
    $product_stock_status = $product->get_stock_status();

    // Modify availability text
    switch ( $product_stock_status ) {
        case 'pre_order':
            $availability = __( 'Pre order', 'woocommerce' );
            break;
        case 'contact_us':
            $availability = __( 'Contact us', 'woocommerce' );
            break;
    }

    return $availability;
}
add_filter( 'woocommerce_get_availability_text', 'filter_woocommerce_get_availability_text', 10, 2 );

/**
 * Modify availability CSS class based on stock status.
 *
 * @param string $class CSS class.
 * @param WC_Product $product Product object.
 * @return string Modified CSS class.
 */
function filter_woocommerce_get_availability_class( $class, $product ) {
    // Get stock status
    $product_stock_status = $product->get_stock_status();

    // Modify CSS class
    switch ( $product_stock_status ) {
        case 'pre_order':
            $class = 'pre-order';
            break;
        case 'contact_us':
            $class = 'contact-us';
            break;
    }

    return $class;
}
add_filter( 'woocommerce_get_availability_class', 'filter_woocommerce_get_availability_class', 10, 2 );

// Admin side
/**
 * Modify stock HTML on admin products list table.
 *
 * @param string  $stock_html Stock HTML.
 * @param WC_Product $product Product object.
 * @return string Modified stock HTML.
 */
function filter_woocommerce_admin_stock_html( $stock_html, $product ) {
    // Simple
    if ( $product->is_type('simple') ) {
        // Get stock status
        $product_stock_status = $product->get_stock_status();
    // Variable
    } elseif ( $product->is_type('variable') ) {
        foreach ( $product->get_visible_children() as $variation_id ) {
            // Get product
            $variation = wc_get_product( $variation_id );

            // Get stock status
            $product_stock_status = $variation->get_stock_status();
             /*
                Currently the status of the last variant in the loop will be displayed.

                So from here you need to add your own logic, depending on what you expect from your custom stock status.

                By default, for the existing statuses. The status displayed on the admin products list table for variable products is determined as:

                - Product should be in stock if a child is in stock.
                - Product should be out of stock if all children are out of stock.
                - Product should be on backorder if all children are on backorder.
                - Product should be on backorder if at least one child is on backorder and the rest are out of stock.
            */
        }
    }

    // Stock status
    switch ( $product_stock_status ) {
        case 'pre_order':
            $stock_html = '<mark class="pre-order" style="background:transparent none;color:#33ccff;font-weight:700;line-height:1;">' . __( 'Pre order', 'woocommerce' ) . '</mark>';
            break;
        case 'contact_us':
            $stock_html = '<mark class="contact-us" style="background:transparent none;color:#cc33ff;font-weight:700;line-height:1;">' . __( 'Contact us', 'woocommerce' ) . '</mark>';
            break;
    }

    return $stock_html;
}
add_filter( 'woocommerce_admin_stock_html', 'filter_woocommerce_admin_stock_html', 10, 2 );</code>

単一製品に追加

カスタム ステータスを作成したら、個々の製品に追加する必要があります。

  1. WordPress 管理画面で変更したい製品に移動します。
  2. 「製品データ」セクションまで下にスクロールします。
  3. [在庫] タブをクリックします。
  4. [在庫ステータス] で、作成したカスタム ステータスを選択します。

フロントエンド ディスプレイ

カスタム在庫ステータスが、サイトのフロントエンド (単一商品ページと商品アーカイブの両方) に表示されるようになります。

トラブルシューティング

カスタム ステータスがフロントエンドまたは管理画面に表示されません。コード スニペットがテーマまたはプラグインに正しく追加されていること、フィルターの名前が正しく設定されていること、およびフィルターが正しくフックされていることを確認してください。

以上がWooCommerce 4 でカスタム在庫ステータスを作成して使用する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
トラフィックの高いウェブサイトのPHPパフォーマンスチューニングトラフィックの高いウェブサイトのPHPパフォーマンスチューニングMay 14, 2025 am 12:13 AM

thesecrettokeepingaphp-poweredwebsterunningsmootlyunderheavyloadinvolvesseveralkeystrategies:1)emform opcodecoduceSciptionexecutiontime、2)aatabasequerycachingwithiThing withiThistolessendavasoload、

PHPでの依存関係注射:初心者向けのコード例PHPでの依存関係注射:初心者向けのコード例May 14, 2025 am 12:08 AM

コードをより明確かつ維持しやすくするため、依存関係が関心(DI)に注意する必要があります。 1)DIは、クラスを切り離すことにより、よりモジュール化されます。2)テストとコードの柔軟性の利便性を向上させ、3)DIコンテナを使用して複雑な依存関係を管理しますが、パフォーマンスの影響と円形の依存関係に注意してください。

PHPパフォーマンス:アプリケーションを最適化することは可能ですか?PHPパフォーマンス:アプリケーションを最適化することは可能ですか?May 14, 2025 am 12:04 AM

はい、最適化されたAphPossibleandessention.1)CachingingusapCutoredatedAtabaseload.2)最適化、効率的なQueries、およびConnectionPooling.3)EnhcodeCodewithBultinctions、Avoididingglobalbariables、およびUsingopcodeching

PHPパフォーマンスの最適化:究極のガイドPHPパフォーマンスの最適化:究極のガイドMay 14, 2025 am 12:02 AM

keyStrategIestsoSificlyvoostphpappliceperformanceare:1)useopcodecachinglikeToreexecutiontime、2)最適化abaseの相互作用とプロペラインデックス、3)3)構成

PHP依存性噴射コンテナ:クイックスタートPHP依存性噴射コンテナ:クイックスタートMay 13, 2025 am 12:11 AM

aphpDependencyInjectionContaineriSATOULTAINATINAGECLASSDEPTINCIES、強化測定性、テスト可能性、および維持可能性。

PHPの依存噴射対サービスロケーターPHPの依存噴射対サービスロケーターMay 13, 2025 am 12:10 AM

SELECT DEPENTENCINGINOFCENT(DI)大規模なアプリケーションの場合、ServicElocatorは小さなプロジェクトまたはプロトタイプに適しています。 1)DIは、コンストラクターインジェクションを通じてコードのテスト可能性とモジュール性を改善します。 2)ServiceLocatorは、センター登録を通じてサービスを取得します。これは便利ですが、コードカップリングの増加につながる可能性があります。

PHPパフォーマンス最適化戦略。PHPパフォーマンス最適化戦略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedforspeedandEfficiencyby:1)enabingopcacheinphp.ini、2)PreparedStatementswithpordatabasequeriesを使用して、3)LoopswithArray_filterandarray_mapfordataprocessing、4)の構成ngincasaSearverseproxy、5)

PHPメールの検証:電子メールが正しく送信されるようにしますPHPメールの検証:電子メールが正しく送信されるようにしますMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

SecLists

SecLists

SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター