programing

Woocommerce - 플러그인을 통해 템플릿 재정의

mailnote 2023. 11. 2. 22:02
반응형

Woocommerce - 플러그인을 통해 템플릿 재정의

질문이 있습니다. 플러그인을 통해 WooCommerce의 기본 템플릿을 테마로 수행하는 것과 동일한 방법으로 재정의할 수 있는 방법이 있습니까?내가 가지고 있는 코드는 다음과.

Class WoocommerceOverride {

    public function woocommerce_locate_template( $template, $template_name, $template_path ) {
        $plugin_path = SPSL_PLUGIN_PATH;
        global $woocommerce;
        $_template = $template;
        if ( ! $template_path ) $template_path = $woocommerce->template_url;
        $plugin_path .= '/woocommerce/';

  // Look within passed path within the theme - this is priority
        $template = locate_template(
            array(
                $template_path . $template_name,
                $template_name
                )
            );

  // Modification: Get the template from this plugin, if it exists
        if ( ! $template && file_exists( $plugin_path . $template_name ) )
            $template = $plugin_path . $template_name;

  // Use default template
        if ( ! $template )
            $template = $_template;

        //echo $template."<br>";

  // Return what we found
        return $template;
    }

}
add_filter( 'woocommerce_locate_template', array('WoocommerceOverride', 'woocommerce_locate_template'), 10, 3 );

이 코드의 문제점은 부분적으로만 작동한다는 것입니다.어떤 부분에서는 작동하고, 다른 부분에서는 작동하지 않습니다.예를 들어 archive-product.php를 사용자 정의할 수 없습니다.코드든 평문이든 거기에 무엇을 쓰든 결과를 얻지 못할 뿐입니다.플러그인 폴더에서 정확히 동일한 템플릿 파일을 테마 폴더에 복사했는데 작동합니다.하지만 플러그인으로 이것이 필요하기 때문에 테마 루트를 갈 수 없습니다.

대단히 고맙습니다.

  • 필터 사용wc_get_template_part기본 WooCommerce 템플릿 부분을 덮어쓸 수 있습니다.
  • 필터 사용woocommerce_locate_template기본 WooCommerce 템플릿을 덮어쓸 수 있습니다.

아래 예시 코드 조각을 시도해 보십시오.

<?php
/**
 * Override default WooCommerce templates and template parts from plugin.
 * 
 * E.g.
 * Override template 'woocommerce/loop/result-count.php' with 'my-plugin/woocommerce/loop/result-count.php'.
 * Override template part 'woocommerce/content-product.php' with 'my-plugin/woocommerce/content-product.php'.
 *
 * Note: We used folder name 'woocommerce' in plugin to override all woocommerce templates and template parts.
 * You can change it as per your requirement.
 */
// Override Template Part's.
add_filter( 'wc_get_template_part',             'override_woocommerce_template_part', 10, 3 );
// Override Template's.
add_filter( 'woocommerce_locate_template',      'override_woocommerce_template', 10, 3 );
/**
 * Template Part's
 *
 * @param  string $template Default template file path.
 * @param  string $slug     Template file slug.
 * @param  string $name     Template file name.
 * @return string           Return the template part from plugin.
 */
function override_woocommerce_template_part( $template, $slug, $name ) {
    // UNCOMMENT FOR @DEBUGGING
    // echo '<pre>';
    // echo 'template: ' . $template . '<br/>';
    // echo 'slug: ' . $slug . '<br/>';
    // echo 'name: ' . $name . '<br/>';
    // echo '</pre>';
    // Template directory.
    // E.g. /wp-content/plugins/my-plugin/woocommerce/
    $template_directory = untrailingslashit( plugin_dir_path( __FILE__ ) ) . 'woocommerce/';
    if ( $name ) {
        $path = $template_directory . "{$slug}-{$name}.php";
    } else {
        $path = $template_directory . "{$slug}.php";
    }
    return file_exists( $path ) ? $path : $template;
}
/**
 * Template File
 *
 * @param  string $template      Default template file  path.
 * @param  string $template_name Template file name.
 * @param  string $template_path Template file directory file path.
 * @return string                Return the template file from plugin.
 */
function override_woocommerce_template( $template, $template_name, $template_path ) {
    // UNCOMMENT FOR @DEBUGGING
    // echo '<pre>';
    // echo 'template: ' . $template . '<br/>';
    // echo 'template_name: ' . $template_name . '<br/>';
    // echo 'template_path: ' . $template_path . '<br/>';
    // echo '</pre>';
    // Template directory.
    // E.g. /wp-content/plugins/my-plugin/woocommerce/
    $template_directory = untrailingslashit( plugin_dir_path( __FILE__ ) ) . 'woocommerce/';
    $path = $template_directory . $template_name;
    return file_exists( $path ) ? $path : $template;
}

몇 달 전에 저는 똑같은 요구사항을 가지고 있었습니다.그래서 인터넷에서 조금 더 검색하고 유용한 코드를 찾았는데, 이 코드는 (요구사항에 따라 사용자 지정을 조금 더 함) 도움이 되었습니다.

자세한 설명 코드는 이것과 이 링크를 확인하세요.접근 방식이 현재 사용하는 방식과 다를 수 있지만 플러그인에서 우커머스 템플릿을 재정의하는 결과를 초래합니다.

이 코드를 추가하기 전에 먼저 시도해 보셔야 합니다.// Use default template코드:

if( $template_name == '{template part name}') {
     $template = $plugin_path . $template_name;
}

내 경우 {template partname}은(는)global/quantity-input.php

코드에 이 줄을 임시로 추가하면 정확한 템플릿 부품 이름을 알 수 있습니다.

print_r($template_name);

답변이 늦었다는 건 알지만 다른 사람에게 유용할지도 모르겠네요.그리고 명심하세요.woocommerce_locate_template은 격이 떨어집니다.따라서 아마도 '최신' 솔루션이 더 많이 존재할 것입니다.

언급URL : https://stackoverflow.com/questions/32150835/woocommerce-overriding-the-template-through-a-plugin

반응형