Как проверить, оставил ли юзер отзывы на товары?
Есть код отсюда: https://misha.agency/woocommerce/kak-otobrazit-vse...
Код создает шорткод [customer_products] который выводит список купленный товаров юзером.
Как правильно сделать проверку через has_reviewed_product ?
Мне нужно, чтобы если в списке товаров показывались только те товары, на которые нет отзыва, от юзера и выводилось echo.
Спасибо за помощь!
add_shortcode( 'customer_products', 'truemisha_products_current_user' ); function truemisha_products_current_user() { // ничего не делаем, если не авторизован if ( ! is_user_logged_in() ) { return; } // получаем все оплаченные заказы пользователя $customer_orders = get_posts( array( 'posts_per_page' => -1, 'meta_key' => '_customer_user', 'meta_value' => get_current_user_id(), 'post_type' => wc_get_order_types(), 'post_status' => array_keys( wc_get_is_paid_statuses() ), ) ); // если заказов не найдено if ( ! $customer_orders ) { return; } // создаём отдельную переменную для ID товаров и записываем в неё $ids = array(); foreach ( $customer_orders as $customer_order ) { $order = wc_get_order( $customer_order->ID ); $items = $order->get_items(); foreach ( $items as $item ) { $ids[] = $item->get_product_id(); } } // возвращаем шорткод return do_shortcode( '[products ids="' . join( ",", array_unique( $ids ) ) . '"]' ); } |
add_shortcode( 'customer_products', 'truemisha_products_current_user' ); function truemisha_products_current_user() { // ничего не делаем, если не авторизован if ( ! is_user_logged_in() ) { return; } // получаем все оплаченные заказы пользователя $customer_orders = get_posts( array( 'posts_per_page' => -1, 'meta_key' => '_customer_user', 'meta_value' => get_current_user_id(), 'post_type' => wc_get_order_types(), 'post_status' => array_keys( wc_get_is_paid_statuses() ), ) ); // если заказов не найдено if ( ! $customer_orders ) { return; } // создаём отдельную переменную для ID товаров и записываем в неё $ids = array(); foreach ( $customer_orders as $customer_order ) { $order = wc_get_order( $customer_order->ID ); $items = $order->get_items(); foreach ( $items as $item ) { $ids[] = $item->get_product_id(); } } // возвращаем шорткод return do_shortcode( '[products ids="' . join( ",", array_unique( $ids ) ) . '"]' ); }
Дополнительно:
add_shortcode( 'customer_products', 'truemisha_products_current_user' ); function truemisha_products_current_user() { // ничего не делаем, если не авторизован if ( ! is_user_logged_in() ) { return; } // получаем все оплаченные заказы пользователя $customer_orders = get_posts( array( 'posts_per_page' => -1, 'meta_key' => '_customer_user', 'meta_value' => get_current_user_id(), 'post_type' => wc_get_order_types(), 'post_status' => array_keys( wc_get_is_paid_statuses() ), ) ); // если заказов не найдено if ( ! $customer_orders ) { return; } // создаём отдельную переменную для ID товаров и записываем в неё $ids = array(); foreach ( $customer_orders as $customer_order ) { $order = wc_get_order( $customer_order->ID ); $items = $order->get_items(); foreach ( $items as $item ) { $product_id = $item->get_product_id(); if ( ! has_reviewed_product( $product_id, get_current_user_id() ) ) { $ids[] = $product_id; } } } // если нет товаров без отзывов if ( empty( $ids ) ) { return; } // возвращаем шорткод return do_shortcode( '[products ids="' . join( ",", array_unique( $ids ) ) . '"]' ); } |
add_shortcode( 'customer_products', 'truemisha_products_current_user' ); function truemisha_products_current_user() { // ничего не делаем, если не авторизован if ( ! is_user_logged_in() ) { return; } // получаем все оплаченные заказы пользователя $customer_orders = get_posts( array( 'posts_per_page' => -1, 'meta_key' => '_customer_user', 'meta_value' => get_current_user_id(), 'post_type' => wc_get_order_types(), 'post_status' => array_keys( wc_get_is_paid_statuses() ), ) ); // если заказов не найдено if ( ! $customer_orders ) { return; } // создаём отдельную переменную для ID товаров и записываем в неё $ids = array(); foreach ( $customer_orders as $customer_order ) { $order = wc_get_order( $customer_order->ID ); $items = $order->get_items(); foreach ( $items as $item ) { $product_id = $item->get_product_id(); if ( ! has_reviewed_product( $product_id, get_current_user_id() ) ) { $ids[] = $product_id; } } } // если нет товаров без отзывов if ( empty( $ids ) ) { return; } // возвращаем шорткод return do_shortcode( '[products ids="' . join( ",", array_unique( $ids ) ) . '"]' ); }
- Спасибо!
Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.
Пока нет других ответов. Будьте первым, кто поможет автору.
Ответить на вопрос

В WooCommerce отзывы на товары — это комментарии типа
reviewк постам типаproduct. Проверять, оставил ли пользователь отзыв, можно черезget_comments()поuser_idи ID товара.Для конкретного товара:
function user_has_reviewed_product($user_id, $product_id) { if (! $user_id || ! $product_id) { return false; } $comments = get_comments([ 'post_id' => $product_id, 'user_id' => $user_id, 'type' => 'review', 'status' => 'approve', 'number' => 1, 'fields' => 'ids', ]); return ! empty($comments); }
Использование:
if (user_has_reviewed_product(get_current_user_id(), get_the_ID())) { echo 'Вы уже оставили отзыв'; } else { echo 'Оставьте отзыв о товаре'; }
Если нужно проверить, оставлял ли пользователь отзывы вообще по магазину, уберите
post_idи добавьтеpost_typeне получится напрямую черезget_comments(). Тогда лучше делать запрос черезWP_Comment_Queryс join к posts или сначала получить товары, где есть комментарии пользователя.Для гостей проверка сложнее: можно сравнивать email, но это ненадёжно. Для бонусов, скидок и ограничений лучше опираться только на авторизованных пользователей.