WordPress как на ладони
Очень Удобный и Быстрый Хостинг для сайтов на WordPress. Пользуюсь сам и вам рекомендую!

wp_star_rating()WP 3.8.0

Выводит HTML рейтинга (звездочки) для указанного рейтинга.

Выводит HTML разметку со звездами от 0 до ... Понимает половины вроде 4.5 звезды...

stars

По умолчанию работает только в админ панели.

1 раз — 0.000057 сек (очень быстро) | 50000 раз — 1.30 сек (быстро) | PHP 7.0.2, WP 4.4.2

Хуков нет.

Возвращает

Строку. HTML код.

Использование

wp_star_rating( $args );
$args(массив)

Массив аргументов для вывода звезд.

  • rating(int)
    Рейтинг который нужно вывести.

    Если в type = rating, то число будет считаться рейтингом и будет выведено количество звезд указанных в этом параметре.

    Если в type = percent, то число будет считаться процентом и будет показано 5 звезд заполненных в соответствии с указанным числом.
    По умолчанию: 0

  • type(string)
    Формат в котором указан параметр $rating. Может быть: rating или percent.
    По умолчанию: 'rating'

  • number(int)
    Число на основе скольки голосов показан результат, добавить в title атрибут тега. Отставьте 0 чтобы не показывать.
    По умолчанию: 0

  • echo(bool)
    Выводить или возвращать результат?
    По умолчанию: true

Примеры

2

#1 Вывод рейтинга (звезд)

Примеры

wp_star_rating( ['rating'=>7.5, 'type'=>'rating', 'number'=>0 ] );

/* Выведет:
<div class="star-rating" title="Рейтинг 7,5"><span class="screen-reader-text">Рейтинг 7,5</span>
	<div class="star star-full"></div>
	<div class="star star-full"></div>
	<div class="star star-full"></div>
	<div class="star star-full"></div>
	<div class="star star-full"></div>
	<div class="star star-full"></div>
	<div class="star star-full"></div>
	<div class="star star-half"></div>
</div>
*/
stars.2
wp_star_rating( ['rating'=>85, 'type'=>'percent', 'number'=>654 ] );

/* Выведет:
<div class="star-rating" title="Рейтинг 4,5 на основе 654 голосов"><span class="screen-reader-text">Рейтинг 4,5 на основе 654 голосов</span>
	<div class="star star-full"></div>
	<div class="star star-full"></div>
	<div class="star star-full"></div>
	<div class="star star-full"></div>
	<div class="star star-half"></div>
</div>
*/

Выглядит так:

stars
0

#2 Вывод во фронт-энде (внешней части)

Во фронт-энде функция не работает и там лучше сделать свою подобную функцию. Но если у вас подключаются шрифты 'dashicons', то есть смысл использовать эту функцию, для этого нужно подключить нужный файл и css стили:

// для фронта
require_once ABSPATH .'wp-admin/includes/template.php';

// подключим иконки
add_action('wp_enqueue_scripts', function(){    wp_enqueue_style('dashicons');    });

// Выводим HTML
wp_star_rating( array( 'rating'=>4.5, 'type'=>'rating', 'number'=>521, ) );

echo '
<style>
.screen-reader-text{ position: absolute; margin: -1px; padding: 0; height: 1px; width: 1px; overflow: hidden; clip: rect(0 0 0 0); border: 0; word-wrap: normal!important; }
.star-rating .star-full:before { content: "\f155"; }
.star-rating .star-half:before { content: "\f459"; }
.star-rating .star-empty:before { content: "\f154"; }
.star-rating .star {
	color: #0074A2;
	display: inline-block;
	font-family: dashicons;
	font-size: 20px;
	font-style: normal;
	font-weight: 400;
	height: 20px;
	line-height: 1;
	text-align: center;
	text-decoration: inherit;
	vertical-align: top;
	width: 20px;
}
</style>';

/* Получим:

<div class="star-rating" data-title="4,5 rating based on 521 ratings">
	<span class="screen-reader-text">4,5 rating based on 521 ratings</span>
	<div class="star star-full"></div>
	<div class="star star-full"></div>
	<div class="star star-full"></div>
	<div class="star star-full"></div>
	<div class="star star-half"></div>
</div>

*/

Список изменений

С версии 3.8.0 Введена.
С версии 4.4.0 Introduced the echo parameter.

Код wp_star_rating() WP 6.5.2

function wp_star_rating( $args = array() ) {
	$defaults    = array(
		'rating' => 0,
		'type'   => 'rating',
		'number' => 0,
		'echo'   => true,
	);
	$parsed_args = wp_parse_args( $args, $defaults );

	// Non-English decimal places when the $rating is coming from a string.
	$rating = (float) str_replace( ',', '.', $parsed_args['rating'] );

	// Convert percentage to star rating, 0..5 in .5 increments.
	if ( 'percent' === $parsed_args['type'] ) {
		$rating = round( $rating / 10, 0 ) / 2;
	}

	// Calculate the number of each type of star needed.
	$full_stars  = floor( $rating );
	$half_stars  = ceil( $rating - $full_stars );
	$empty_stars = 5 - $full_stars - $half_stars;

	if ( $parsed_args['number'] ) {
		/* translators: Hidden accessibility text. 1: The rating, 2: The number of ratings. */
		$format = _n( '%1$s rating based on %2$s rating', '%1$s rating based on %2$s ratings', $parsed_args['number'] );
		$title  = sprintf( $format, number_format_i18n( $rating, 1 ), number_format_i18n( $parsed_args['number'] ) );
	} else {
		/* translators: Hidden accessibility text. %s: The rating. */
		$title = sprintf( __( '%s rating' ), number_format_i18n( $rating, 1 ) );
	}

	$output  = '<div class="star-rating">';
	$output .= '<span class="screen-reader-text">' . $title . '</span>';
	$output .= str_repeat( '<div class="star star-full" aria-hidden="true"></div>', $full_stars );
	$output .= str_repeat( '<div class="star star-half" aria-hidden="true"></div>', $half_stars );
	$output .= str_repeat( '<div class="star star-empty" aria-hidden="true"></div>', $empty_stars );
	$output .= '</div>';

	if ( $parsed_args['echo'] ) {
		echo $output;
	}

	return $output;
}
12 комментариев
Полезные 2 Все
    Войти