bestsource

사용자 지정 위젯에서 woocommerce 미니 카트의 사용자 지정 템플릿을 로드하는 방법

bestsource 2023. 2. 23. 22:58
반응형

사용자 지정 위젯에서 woocommerce 미니 카트의 사용자 지정 템플릿을 로드하는 방법

WooCommerce Mini Cart용 커스텀 위젯을 만들고 싶은데 WC의 기본 Mini Cart 위젯도 유지하고 싶기 때문에 mini-cart.php를 테마에 복사하여 템플릿 오버라이드를 하고 싶지 않습니다.플러그인 위젯 디렉토리(plugins/woocommerce/includes/widgets/class-wc-widget-cart.php)에서 위젯 클래스를 복사하고 mini-cart.php의 기본 코드를 mini-cart.php라는 내 테마 디렉토리 아래에 복사하여 미니 카트의 새로운 템플릿 파일을 만들었습니다.이제 위젯용 템플릿 파일을 로드합니다.현재 사용하고 있는 위젯 클래스는 보시는 바와 같이 핵심 위젯의 클래스와 매우 유사합니다.

class WC_Dropdown_Cart extends WC_Widget {

    public function __construct() {
        $this->widget_cssclass    = 'woocommerce widget_shopping_cart';
        $this->widget_description = __( "Custom Mini Cart", 'woocommerce' );
        $this->widget_name        = __( 'Custom Mini Cart', 'woocommerce' );
        $this->widget_id          = 'woocommerce_widget_custom_mini_cart';
        $this->settings           = array(
            'title'  => array(
                'type'  => 'text',
                'std'   => __( 'Cart', 'woocommerce' ),
                'label' => __( 'Title', 'woocommerce' )
            ),
            'hide_if_empty' => array(
                'type'  => 'checkbox',
                'std'   => 0,
                'label' => __( 'Hide if cart is empty', 'woocommerce' )
            )
        );
        parent::__construct();
    }

    function widget( $args, $instance ) {
    if ( is_cart() || is_checkout() ) {
        return;
    }

        $hide_if_empty = empty( $instance['hide_if_empty'] ) ? 0 : 1;

        $this->widget_start( $args, $instance );

        if ( $hide_if_empty ) {
            echo '<div class="hide_cart_widget_if_empty">';
        }

        // Insert cart widget placeholder - code in woocommerce.js will update this on page load
        echo '<div class="widget_shopping_cart_content"></div>';

        if ( $hide_if_empty ) {
            echo '</div>';
        }

        $this->widget_end( $args );
    }

}

WooCommerce가 클래스의 위젯 함수 내에서 해당 파일을 호출하는 시점은 다음과 같습니다.

echo '<div class="widget_shopping_cart_content"></div>';

하지만 WooCommerce는 javascript 방식으로 작업을 수행하지만, 저는 작업을 수행할 수 없습니다.여기서 그것을 하기 위한 절차는 무엇입니까?

보다 간단한 해결책은 WooCommerce Hooks를 사용하는 것입니다.

https://woocommerce.github.io/code-reference/namespaces/default.html

미니 카트 후크:

https://woocommerce.github.io/code-reference/namespaces/default.html#function_woocommerce_mini_cart

WooCommerce 원래 코드에서 복사 및 수정한 코드를 사용자용으로 커스텀템플릿을 만든 후 다음 작업을 사용하여 WooCommerce 기본값을 삭제할 수 있습니다.

remove_action( 'woocommerce_after_mini_cart', 'action_woocommerce_after_mini_cart', 10, 0 );

로딩합니다.template/file대신 다음 작업을 사용합니다.

add_action( 'woocommerce_after_mini_cart', get_template_part('your-template-path'), 10, 0 );

WooCommerce에는 테마 개발에 활용할 수 있는 매우 좋은 훅이 있습니다.모든 훅을 보려면 첫 번째 링크를 확인해 주세요.

해피 코딩 :)

언급URL : https://stackoverflow.com/questions/31114538/how-to-load-custom-template-for-woocommerce-mini-cart-in-custom-widget

반응형