Проводим различные эксперименты и манипуляции с меню.
Добавить пункт функцией
Добавляем произвольный пункт меню при помощи функции (!данный пример будет работать только с установленным плагином woocommerce)
add_filter( 'wp_nav_menu_items', 'my_account_loginout_link', 10, 2 );
function my_account_loginout_link( $items, $args ) {
if (is_user_logged_in() && $args->theme_location == 'header-menu') { //change your theme location menu to suit
$items .= '<li><a class="nav-link" href="'. wp_logout_url( get_permalink( wc_get_page_id( 'shop' ) ) ) .'">Sair</a></li>'; //change logout link, here it goes to 'shop', you may want to put it to 'myaccount'
}
elseif (!is_user_logged_in() && $args->theme_location == 'header-menu') {//change your theme location menu to suit
$items .= '<li><a class="nav-link" href="' . get_permalink( wc_get_page_id( 'myaccount' ) ) . '">Entrar</a></li>';
}
return $items;
}
В данном случае добавляется пункт ВХОД/ВЫХОД, но главное — принцип внедрения пункта меню.
Вывод цикла через функцию
function conclusion_while() {
global $post;
$args = array(
'posts_per_page' => 5
);
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post);
echo '<a href="'.the_permalink().'">'.the_title().'</a>';
endforeach;
wp_reset_postdata();
}
add_action('body-after', 'conclusion_while');
Таким образом мы можем вывести произвольный цикл практически в любом месте на сайте, например в меню, но делать это нужно особым образом — об этом далее.
Последние записи в меню
Выводим пункт меню «Последние записи» с динамическими подпунктами записями
function conclusion_while($items, $args) {
$lastposts = "";
if ($args->theme_location == 'header-menu') { //в каком меню выводить
global $post;
$args = array(
'posts_per_page' => 5
);
$myposts = get_posts( $args );
$lastposts .= '<li class="menu-item menu-item-has-children"><a href="/#">Последние записи</a>';
$lastposts .= '<ul class="sub-menu">';
foreach( $myposts as $post ) : setup_postdata($post);
$lastposts .= '<li class="menu-item menu-item-type-custom menu-item-object-custom">';
$lastposts .= '<a href="';
$lastposts .= get_the_permalink();
$lastposts .= '">';
$lastposts .= get_the_title();
$lastposts .= '</a>';
$lastposts .= '</li>';
endforeach;
$lastposts .= '</ul>';
$lastposts .= '</li>';
wp_reset_postdata();
$items = $items . $lastposts;
}
return $items;
}
add_filter('wp_nav_menu_items', 'conclusion_while', 10, 2);
if ($args->theme_location == ‘header-menu’) { — этим условием мы локализуем данную функцию на конкретное меню. Если это условие не установить, то функция будет воздействовать на все существующие меню.
В данном случае новый пункт добавиться в конце, чтобы добавить его в начале — нужно переменные поменять местами: $items = $lastposts . $items;
Альтернативный синтаксис вывода единицы цикла (на заметку):
$lastposts .= '<li class="menu-item menu-item-type-custom menu-item-object-custom">'
. '<a href="'
. get_the_permalink()
. '">'
. get_the_title()
. '</a>'
. '</li>';
Вывод в пункте меню количество наименований товаров
Выведем в меню часть функционала мини-корзины, а именно количество наименований.
// Добавим пункт Корзина с кол-вом наименований в меню
function new_nav_menu_items($items) {
$homelink = '<li><a href="/cart/">Корзина <span class="cart-counter"></span></a></li>';
$items = $items . $homelink;
return $items;
}
add_filter( 'wp_nav_menu_items', 'new_nav_menu_items' );
//Ajax Обновление кол-ва наименований
add_filter( 'woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment' );
function woocommerce_header_add_to_cart_fragment( $fragments ) {
ob_start(); ?>
<span class="cart-counter"><?php name_item_in_cart_count(); ?></span>
<?php $fragments['.cart-counter'] = ob_get_clean();
return $fragments;
}
//Определяем кол-во наименований
function name_item_in_cart_count() {
global $woocommerce;
$product_ids = array();
foreach(WC()->cart->get_cart() as $cart_item_key => $values) { $product_ids[] = $values['product_id']; }
$product_ids_unique = array_unique($product_ids);
if (count($product_ids_unique) > 0) { echo count($product_ids_unique); }
}
При «0» количество не будет выводится.
Стиль количества:
span.cart-counter {
background: #fff;
color: #222;
width: 20px;
line-height: 20px;
display: inline-block;
text-align: center;
border-radius: 10px;
font-size: 0.8rem;
}
[site-socialshare]