搜尋
首頁後端開發php教程如何在 WooCommerce 4 中建立和使用自訂庫存狀態?

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

如何向WooCommerce 4 中的產品添加自定義庫存狀態

背景

WooCommerce預設提供多種庫存狀態,包括有貨、缺貨和缺貨。但是,您可能需要建立自訂庫存狀態來滿足您的特定庫存管理需求。

建立自訂庫存狀態

要建立自訂庫存狀態,請使用下列程式碼主題的functions.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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
高流量網站的PHP性能調整高流量網站的PHP性能調整May 14, 2025 am 12:13 AM

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

PHP中的依賴注入:初學者的代碼示例PHP中的依賴注入:初學者的代碼示例May 14, 2025 am 12:08 AM

你應該關心DependencyInjection(DI),因為它能讓你的代碼更清晰、更易維護。 1)DI通過解耦類,使其更模塊化,2)提高了測試的便捷性和代碼的靈活性,3)使用DI容器可以管理複雜的依賴關係,但要注意性能影響和循環依賴問題,4)最佳實踐是依賴於抽象接口,實現鬆散耦合。

PHP性能:是否可以優化應用程序?PHP性能:是否可以優化應用程序?May 14, 2025 am 12:04 AM

是的,優化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)優化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,並避免使用

PHP性能優化:最終指南PHP性能優化:最終指南May 14, 2025 am 12:02 AM

theKeyStrategiestosigantificallyBoostPhpaPplicationPerformenCeare:1)UseOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)優化AtabaseInteractionswithPreparedStateTementStatementStatementAndProperIndexing,3)配置

PHP依賴注入容器:快速啟動PHP依賴注入容器:快速啟動May 13, 2025 am 12:11 AM

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增強codemodocultion,可驗證性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

PHP中的依賴注入與服務定位器PHP中的依賴注入與服務定位器May 13, 2025 am 12:10 AM

選擇DependencyInjection(DI)用於大型應用,ServiceLocator適合小型項目或原型。 1)DI通過構造函數注入依賴,提高代碼的測試性和模塊化。 2)ServiceLocator通過中心註冊獲取服務,方便但可能導致代碼耦合度增加。

PHP性能優化策略。PHP性能優化策略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)啟用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替換loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

PHP電子郵件驗證:確保正確發送電子郵件PHP電子郵件驗證:確保正確發送電子郵件May 13, 2025 am 12:06 AM

phpemailvalidation invoLvesthreesteps:1)格式化進行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器