搜索
首页后端开发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

theKeyStrategiestosiminificallyBoostphpapplicationPermenCeare:1)useOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)优化AtabaseInteractionswithPreparedStateTemtStatementStatementSandProperIndexing,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

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。