在 WooCommerce 中为自定义库存状态创建自定义简码

问题描述 投票:0回答:0

我目前使用以下 PHP 为我的预购产品自动生成自定义库存状态,在 WooCommerce 中显示状态“可预购”。

工作得很好,但是我希望能够在我网站的 html 内容区域中添加自定义库存状态作为简码。

这里是我目前使用的PHP:

/**
 * Change availability text.
 *
 * @param array      $availability  Availability data array.
 * @param WC_Product $_product      WC Product object.
 *
 * @return array.
 */
function wcs_custom_get_availability( $availability, $_product ) {
    $is_preorder = 'no';

    if ( $_product->is_type( 'variation' ) ) {
        $is_preorder = get_post_meta( $_product->get_id(), '_wpro_variable_is_preorder', true );
    } elseif ( $_product->is_type( 'variable' ) ) {
        $_variations     = $_product->get_available_variations();
        $_variations_ids = ! empty( $_variations ) ? wp_list_pluck( $_variations, 'variation_id' ) : array();
        if ( ! empty( $_variations_ids ) ) {
            $is_preorders = array_map(
                function( $id ) {
                    return wc_string_to_bool( get_post_meta( $id, '_wpro_variable_is_preorder', true ) );
                },
                $_variations_ids
            );
            $is_preorder  = in_array( true, $is_preorders, true ) ? 'yes' : 'no';
        }
    } else {
        $is_preorder = get_post_meta( $_product->get_id(), '_simple_preorder', true );
    }

    if ( wc_string_to_bool( $is_preorder ) ) {
        $availability['availability'] = __( 'Available for Pre-Order', 'woocommerce' );
    }

    return $availability;
}
add_action( 'woocommerce_get_availability', 'wcs_custom_get_availability', 20, 2 ); 

我试图通过结合上面代码的各个方面来修改下面的 PHP,但没有成功:

add_shortcode( 'stock_status', 'display_product_stock_status' );
function display_product_stock_status( $atts) {

    $atts = shortcode_atts(
        array('id'  => get_the_ID() ),
        $atts, 'stock_status'
    );

    $product = wc_get_product( $atts['id'] );

    $stock_status = $product->get_stock_status();

    if ( 'instock' == $stock_status) {
        return '<p class="stock in-stock">In stock</p>';
    } else {
        return '<p class="stock out-of-stock">Out of stock</p>';
    }
 }

在上面的示例中,简码输入为 [stock_status id='47'](此示例中的 47 是产品 ID)。

如果有人可以就如何将两者结合起来提供建议,我将不胜感激(很乐意根据需要提供额外的上下文)。

php wordpress woocommerce shortcode
© www.soinside.com 2019 - 2024. All rights reserved.