Как использовать код шаблона Woocommerce в файле functions.php темы - PullRequest
0 голосов
/ 25 сентября 2018

Я хочу показать подсчет количества отзывов по каждому продукту woocommerce, поэтому я перешел по этой ссылке , и она работает для всех продуктов.

но я также добавил раздел недавних обзоров с помощью другого плагина.где счетное число не отображается.

Причина в том, что плагин не обнаружил код ratting.php, поэтому я хочу знать, как я могу использовать код rating.php в файле functions.php темы.Другими словами, слова, Как я могу преобразовать этот код как функции, чтобы я мог использовать его в файле functions.php

, вот код rating.php

<?php
/**
 * Loop Rating
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/loop/rating.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see         https://docs.woocommerce.com/document/template-structure/
 * @author      WooThemes
 * @package     WooCommerce/Templates
 * @version     3.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

global $product;

if ( get_option( 'woocommerce_enable_review_rating' ) === 'no' ) {
    return;
}

$rating_count = $product->get_rating_count();
$review_count = $product->get_review_count();
$average      = $product->get_average_rating();

if ( $rating_count >= 0 ) : ?>

            <?php echo wc_get_rating_html($average, $rating_count); ?>
        <?php if ( comments_open() ): ?><a href="<?php echo get_permalink() ?>#reviews" class="woocommerce-review-link" rel="nofollow">(<?php printf( _n( '%s',$review_count,'woocommerce' ), '<span class="count">' . esc_html( $review_count ) . '</span>' ); ?>)</a><?php endif ?>


<?php endif; ?>

Спасибо

1 Ответ

0 голосов
/ 26 сентября 2018

Вы можете встроить код в функцию в виде короткого кода с аргументом id (идентификатор продукта) :

add_shortcode( 'product_rating', 'display_product_rating' );
function display_product_rating( $atts ){
    // Shortcode attributes (default)
    $atts = shortcode_atts( array(
        'id' => '0',
    ), $atts, 'product_rating' );

    if ( get_option( 'woocommerce_enable_review_rating' ) === 'no' )
        return; // Exit

    global $product, $post;

    if( ! is_a( $product, 'WC_product') ){
        $product_id   = $atts['id'] > 0 ? $atts['id'] : get_the_id();
        $product      = wc_get_product( $product_id );
        if( ! is_a( $product, 'WC_product') ) 
            return; // Exit
    }

    $rating_count = $product->get_rating_count();
    $review_count = $product->get_review_count();
    $average      = $product->get_average_rating();
    $output       = '';

    if ( $rating_count >= 0 ) {
        $output .= wc_get_rating_html($average, $rating_count);
        if ( comments_open() ) {
            $fcount = $printf( _n( '%s',$review_count,'woocommerce' ), '<span class="count">' . esc_html( $review_count ) . '</span>' );
            $output .= '<a href="'.get_permalink().'#reviews" class="woocommerce-review-link" rel="nofollow">('.$fcount.')</a>';
        }
    }
    return $output;
}

Код входит вФайл function.php активной дочерней темы (или активной темы).Протестировано и работает.


ПРИМЕРЫ ИСПОЛЬЗОВАНИЯ:

1) В текстовом редакторе WordPress поста или страницы, определяя id аргумент (идентификатор продукта) :

[product_rating id='37']

2) В некотором php-коде с dynamic $product_id variable (код продукта) :

echo do_shortcode( "[product_rating id='$product_id']" );

3) Внутри цикла продукта WP_Query или WC_Product_Query:

echo do_shortcode( "[product_rating]" );
...