Функции плагина доступны только для настраиваемого типа сообщения

Я новый разработчик. Я столкнулся с проблемой. Я активировал плагин для оценки комментариев. Теперь он отображается на всех типах страниц сообщений. Но я хочу показать, что этот комментарий оценивается только для моего пользовательского типа сообщения xyz. Как я могу это сделать? Я использовал этот код, чтобы включить add_action, если тип сообщения xyz в плагине для комментариев, но он не работает. Плагин

add_action('save_post','save_post_callback');
function save_post_callback($post_id){
    global $post; 
    if ($post->post_type = 'xyz'){
        add_action( 'comment_form_logged_in_after', 'ci_comment_rating_rating_field' );
        add_action( 'comment_form_after_fields', 'ci_comment_rating_rating_field' );
        return;
    }
    //if you get here then it's your post type so do your thing....
}

Это действительно зависит от плагина. Разные плагины позволяют это делать по-разному. Вы пробовали форумы поддержки плагинов?

Howdy_McGee 10.09.2018 06:18

Это как ваш вопрос wordpress.stackexchange.com/questions/26202/…

Ramesh 10.09.2018 06:19

@Howdy_McGee Я использовал этот плагин ссылка

Kane 10.09.2018 06:26

вы хотите рейтинг в админке или на интерфейсе?

Vel 10.09.2018 07:16

@Vel Он отображается во внешнем интерфейсе и работает хорошо. Я хочу, чтобы он отображал только мои настраиваемые разделы комментариев к сообщениям, но он отображался во всех сообщениях, разделах настраиваемых комментариев к сообщениям.

Kane 10.09.2018 07:22
Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Symfony Station Communiqué - 7 июля 2023 г
Symfony Station Communiqué - 7 июля 2023 г
Это коммюнике первоначально появилось на Symfony Station .
Оживление вашего приложения Laravel: Понимание режима обслуживания
Оживление вашего приложения Laravel: Понимание режима обслуживания
Здравствуйте, разработчики! В сегодняшней статье мы рассмотрим важный аспект управления приложениями, который часто упускается из виду в суете...
Установка и настройка Nginx и PHP на Ubuntu-сервере
Установка и настройка Nginx и PHP на Ubuntu-сервере
В этот раз я сделаю руководство по установке и настройке nginx и php на Ubuntu OS.
Коллекции в Laravel более простым способом
Коллекции в Laravel более простым способом
Привет, читатели, сегодня мы узнаем о коллекциях. В Laravel коллекции - это способ манипулировать массивами и играть с массивами данных. Благодаря...
Как установить PHP на Mac
Как установить PHP на Mac
PHP - это популярный язык программирования, который используется для разработки веб-приложений. Если вы используете Mac и хотите разрабатывать...
1
5
98
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Попробуйте этот код

<?php
/*
Plugin Name: CI Comment Rating
Description: Adds a star rating system to WordPress comments
Version: 1.0.0
Author: The CSSIgniter Team
Author URI: https://cssigniter.com/
*/
//Enqueue the plugin's styles.
add_action( 'wp_enqueue_scripts', 'ci_comment_rating_styles' );
function ci_comment_rating_styles() {
    wp_register_style( 'ci-comment-rating-styles', plugins_url( '/', __FILE__ ) . 'assets/style.css' );
    wp_enqueue_style( 'dashicons' );
    wp_enqueue_style( 'ci-comment-rating-styles' );
}


//Create the rating interface.
add_action( 'comment_form_logged_in_after', 'ci_comment_rating_rating_field' );
add_action( 'comment_form_after_fields', 'ci_comment_rating_rating_field' );

function ci_comment_rating_rating_field () {
  global $post_type;
    if ($post_type =='xyz'){

    ?>
    <label for = "rating">Rating<span class = "required">*</span></label>
    <fieldset class = "comments-rating">
        <span class = "rating-container">
            <?php for ( $i = 5; $i >= 1; $i-- ) : ?>
                <input type = "radio" id = "rating-<?php echo esc_attr( $i ); ?>" name = "rating" value = "<?php echo esc_attr( $i ); ?>" /><label for = "rating-<?php echo esc_attr( $i ); ?>"><?php echo esc_html( $i ); ?></label>
            <?php endfor; ?>
            <input type = "radio" id = "rating-0" class = "star-cb-clear" name = "rating" value = "0" /><label for = "rating-0">0</label>
        </span>
    </fieldset>
    <?php
    }
}
//Save the rating submitted by the user.
add_action( 'comment_post', 'ci_comment_rating_save_comment_rating' );
function ci_comment_rating_save_comment_rating( $comment_id ) {
    if ( ( isset( $_POST['rating'] ) ) && ( '' !== $_POST['rating'] ) )
    $rating = intval( $_POST['rating'] );
    add_comment_meta( $comment_id, 'rating', $rating );
}
//Make the rating required.
add_filter( 'preprocess_comment', 'ci_comment_rating_require_rating' );
function ci_comment_rating_require_rating( $commentdata ) {
    if ( ! isset( $_POST['rating'] ) || 0 === intval( $_POST['rating'] ) )
    wp_die( __( 'Error: You did not add a rating. Hit the Back button on your Web browser and resubmit your comment with a rating.' ) );
    return $commentdata;
}
//Display the rating on a submitted comment.
add_filter( 'comment_text', 'ci_comment_rating_display_rating');
function ci_comment_rating_display_rating( $comment_text ){
    if ( $rating = get_comment_meta( get_comment_ID(), 'rating', true ) ) {
        $stars = '<p class = "stars">';
        for ( $i = 1; $i <= $rating; $i++ ) {
            $stars .= '<span class = "dashicons dashicons-star-filled"></span>';
        }
        $stars .= '</p>';
        $comment_text = $comment_text . $stars;
        return $comment_text;
    } else {
        return $comment_text;
    }
}
// Collect post dating data.
function ci_comment_rating_get_ratings_data( $id ) {
    $comments = get_approved_comments( $id );
    if ( $comments ) {
        $i = 0;
        $total = 0;
        foreach( $comments as $comment ){
            $rate = get_comment_meta( $comment->comment_ID, 'rating', true );
            if ( isset( $rate ) && '' !== $rate ) {
                $i++;
                $total += $rate;
            }
        }
        if ( 0 === $i ) {
            return false;
        } else {
            return $rating_data = array(
                'reviews' => $i,
                'total'   => $total,
            );
        }
    } else {
        return false;
    }
}
//Display the average rating above the content.
add_filter( 'the_content', 'ci_comment_rating_display_average_rating' );
function ci_comment_rating_display_average_rating( $content ) {
    global $post;
    if ( false === ci_comment_rating_get_ratings_data( $post->ID ) ) {
        return $content;
    }
    $stars       = '';  
    $rating_data = ci_comment_rating_get_ratings_data( $post->ID );
    $average     = round( $rating_data['total'] / $rating_data['reviews'], 1 );;
    for ( $i = 1; $i <= $average + 1; $i++ ) {
        $width = intval( $i - $average > 0 ? 20 - ( ( $i - $average ) * 20 ) : 20 );
        if ( 0 === $width ) {
            continue;
        }
        $stars .= '<span style = "overflow:hidden; width:' . $width . 'px" class = "dashicons dashicons-star-filled"></span>';
        if ( $i - $average > 0 ) {
            $stars .= '<span style = "overflow:hidden; position:relative; left:-' . $width .'px;" class = "dashicons dashicons-star-empty"></span>';
        }
    }
    $custom_content  = '<p class = "average-rating">This post\'s average rating is: ' . $average .' ' . $stars .' calculated from '. $rating_data['reviews'] .' reviews.</p>';
    $custom_content .= $content;
    return $custom_content;
}

Я обновил приведенный ниже код в функции ci_comment_rating_rating_field.

 global $post_type;
  if ($post_type =='xyz'){

Теперь рейтинг отображается на моей индивидуальной странице сообщения, но если я прокомментирую одну страницу сообщения блога по умолчанию, показывающую эту ошибку Error: You did not add a rating. Hit the Back button on your Web browser and resubmit your comment with a rating.

Kane 10.09.2018 09:40

добавить то же условие if в эту функцию ci_comment_rating_require_rating

Vel 10.09.2018 09:54

Вы можете посмотреть это ссылка

Kane 12.09.2018 08:58

@Kane, дай проверить.

Vel 12.09.2018 09:18

Другие вопросы по теме