php 允许您以编程方式(动态)将菜单项添加到WordPress菜单。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 允许您以编程方式(动态)将菜单项添加到WordPress菜单。相关的知识,希望对你有一定的参考价值。
<?php
// 1 вариант
add_filter( 'wp_get_nav_menu_items', function ( $items ) {
$locations = get_nav_menu_locations();
if ( ! is_admin() && isset( $locations['main_menu'] ) ) {
$cats = get_categories();
foreach ( $cats as $cat ) {
$item = new WP_Post( new stdClass() );
$item->title = $cat->name;
$item->url = get_category_link( $cat );
$item->db_id = $cat->term_id;
$item->object_id = $cat->term_id;
$item->object = $cat->taxonomy;
$item->type = 'taxonomy';
$item->target = '';
$item->attr_title = '';
$item->description = '';
$item->classes = [];
$item->xfn = '';
$items[] = $item;
$posts = get_posts( [ 'category' => $cat->term_id ] );
foreach ( $posts as $post ) {
$post->url = get_permalink( $post );
$post->title = $post->post_title;
$post->menu_item_parent = $cat->term_id;
$post->object_id = $post->ID;
$post->object = $post->post_type;
$post->type = 'post_type';
$post->target = '';
$post->attr_title = '';
$post->description = '';
$post->classes = [];
$post->xfn = '';
$items[] = $post;
}
}
array_map( function ( $item_menu ) {
static $index = 0;
$item_menu->menu_order = ++ $index;
return $item_menu;
}, $items );
}
return $items;
} );
// Вариант 2
add_filter( 'wp_nav_menu_objects', function ( $items, $args ) {
if ( ! is_admin() && $args->theme_location === 'top' ) {
$cats = get_categories();
foreach ( $cats as $cat ) {
$item = new WP_Post( new stdClass() );
$item->ID = $cat->term_id;
$item->title = $cat->name;
$item->url = get_category_link( $cat );
$item->object_id = $cat->term_id;
$item->object = $cat->taxonomy;
$item->type = 'taxonomy';
$item->target = '';
$item->attr_title = '';
$item->description = '';
$item->classes = [];
$item->xfn = '';
$items[] = $item;
}
_wp_menu_item_classes_by_context( $items );
}
return $items;
}, 10, 2 );
以上是关于php 允许您以编程方式(动态)将菜单项添加到WordPress菜单。的主要内容,如果未能解决你的问题,请参考以下文章
php WordPress类可以轻松地将自定义菜单项动态添加到菜单中。
使用动作选择器预设将项目添加到 NSMenu
如何将消息映射添加到 MFC 中的动态菜单项
如何将选项检查菜单添加到 CMFCToolBar 以允许同时进行多项检查
以编程方式膨胀底部导航视图菜单
在显示之前将动态自定义 UIMenuItem 添加到复制和粘贴菜单