Woocommerce хлебные крошки нескольких категорий

У меня есть сайт электронной коммерции в WordPress. В нем много продуктов & многие продукты относятся к нескольким категориям, например, 600 мАч. Банк питания относится к автомобильным, ИТ, медиа и т. д. Моя проблема заключается в том, что когда я перехожу к деталям продукта, он по умолчанию выбирает только одну категорию, независимо от того, идет ли он по категории ИТ в в конце он показывает мне автомобиль, как этот Главная / Магазин / Промышленность / Автомобиль / 600 мАч Power Bank. Но я пошел к этому продукту через ИТ, поэтому он должен показывать мне, как этот дом / магазин / промышленность / IT / 600 мАч Power Bank.
Как я могу найти путь, откуда я пришел с предыдущей страницы?

4

Решение

Если вы используете WooCommerce, вы можете использовать следующее напрямую, в противном случае вам потребуется адаптация, но вы поняли:

elseif ( is_single() && ! is_attachment() ) {

if ( get_post_type() == 'product' ) {

echo $prepend;

if ( $terms = get_the_terms( $post->ID, 'product_cat' ) ) {

$referer = wp_get_referer();
foreach( $terms as $term){
$referer_slug = (strpos($referer, $term->slug));

if(!$referer_slug==false){
$category_name = $term->name;
$ancestors = get_ancestors( $term->term_id, 'product_cat' );
$ancestors = array_reverse( $ancestors );

foreach ( $ancestors as $ancestor ) {
$ancestor = get_term( $ancestor, 'product_cat' );

if ( ! is_wp_error( $ancestor ) && $ancestor )
echo $before . '<a href="' . get_term_link( $ancestor->slug, 'product_cat' ) . '">' . $ancestor->name . '</a>' . $after . $delimiter;
}
echo $before . '<a href="' . get_term_link( $term->slug, 'product_cat' ) . '">' . $category_name . '</a>' . $after . $delimiter;
}
}
}

echo $before . get_the_title() . $after;

Основная часть работы здесь выполняется wp_get_referer который получает ссылающийся URL продукта, на который перешел ваш посетитель. Остальная часть кода проверяет, содержится ли в URL допустимая категория, и использует ее в крошке.

См. Jonathon Js сообщение здесь для получения дополнительной информации http://www.cryoutcreations.eu/forums/t/wrong-breadcrumbs-displayed

1

Другие решения

Мое решение:

if (! empty ($ breadcrumb)) {

echo $wrap_before;

if (is_single() && get_post_type() == 'product') {
$breadcrumb_diff = [];
$breadcrumb_diff[] = $breadcrumb[0];
if ($terms = get_the_terms($post->ID, 'product_cat')) {
$referer = wp_get_referer();
$site_url = site_url();
$referer = str_replace($site_url . '/zoomagazin/', '', $referer);
$referer_array = explode('/', $referer);
foreach ($referer_array as $term_slug) {
$get_term_by_slug = get_term_by('slug', $term_slug, 'product_cat');
$breadcrumb_diff[] = [$get_term_by_slug->name, get_term_link($term_slug, 'product_cat')];
}
$breadcrumb_diff[]= $breadcrumb[count($breadcrumb) - 1];

foreach ($breadcrumb_diff as $key => $crumb) {

echo $before;

if (!empty($crumb[1]) && sizeof($breadcrumb_diff) !== $key + 1) {
echo '<a href="' . esc_url($crumb[1]) . '">' . esc_html($crumb[0]) . '</a>';
} else {
echo esc_html($crumb[0]);
}

echo $after;

if (sizeof($breadcrumb) !== $key + 1) {
echo $delimiter;
}

}
}
} else {foreach ($breadcrumb as $key => $crumb) {

echo $before;

if (!empty($crumb[1]) && sizeof($breadcrumb) !== $key + 1) {
echo '<a href="' . esc_url($crumb[1]) . '">' . esc_html($crumb[0]) . '</a>';
} else {
echo esc_html($crumb[0]);
}

echo $after;

if (sizeof($breadcrumb) !== $key + 1) {
echo $delimiter;
}

}
}

echo $wrap_after;

}

0

Обновленный ответ для тех, кто все еще сталкивается с этой проблемой на более новой версии WooCommerce, это решение работало для меня на WooCommerce 3.5.4.

Этот код должен быть помещен в следующий путь к файлу (то есть дочерняя тема)
/wp-content/themes/your-child-theme/woocommerce/global/breadcrumb.php

Он переопределит стандартный код WooCommerce.

http://pastebin.com/raw/bemM8ZNF

/**
* Shop breadcrumb
*
* This template can be overridden by copying it to yourtheme/woocommerce/global/breadcrumb.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     2.3.0
* @see         woocommerce_breadcrumb()

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

if ( $breadcrumb ) {

echo $wrap_before;

if ( is_single() && get_post_type() == 'product' ) {

echo $prepend;

if ( $terms = get_the_terms( $post->ID, 'product_cat' ) ) {

$referer = wp_get_referer();

$printed = array();

foreach( $terms as $term){

if(in_array($term->id, $printed)) continue;

$referer_slug = (strpos($referer, '/'.$term->slug.'/'));

if(!$referer_slug==false){

$printed[] = $term->id;

$category_name = $term->name;
$ancestors = get_ancestors( $term->term_id, 'product_cat' );
$ancestors = array_reverse( $ancestors );

foreach ( $ancestors as $ancestor ) {
$ancestor = get_term( $ancestor, 'product_cat' );

if ( ! is_wp_error( $ancestor ) && $ancestor )
echo $before . '<a href="' . get_term_link( $ancestor->slug, 'product_cat' ) . '">' . $ancestor->name . '</a>' . $after . $delimiter;
}

echo $before . '<a href="' . get_term_link( $term->slug, 'product_cat' ) . '">' . $category_name . '</a>' . $after . $delimiter;
}
}

}

echo $before . get_the_title() . $after;

} else {

foreach ( $breadcrumb as $key => $crumb ) {

echo $before;

if ( ! empty( $crumb[1] ) && sizeof( $breadcrumb ) !== $key + 1 ) {
echo '<a href="' . esc_url( $crumb[1] ) . '">' . esc_html( $crumb[0] ) . '</a>';
} else {
echo esc_html( $crumb[0] );
}

echo $after;

if ( sizeof( $breadcrumb ) !== $key + 1 ) {
echo $delimiter;
}

}
}

echo $wrap_after;

}

С / О: Йорис Виттеман

0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector