WordPress主题开发教程PHP版
Published
2023-03-10
浏览次数 : 195
替换菜单
然后我们来替换前端的菜单。我们先在后台,找到页面,新建页面,新建几个,比方说home,blog,about,contact,products。
然后我们在framework下面的functions下面新建setup.php文件,在文件里新建函数:
function haqiye_setup() {
/*
* Make theme available for translation.
* Translations can be filed in the /languages/ directory.
* If you're building a theme based on haqiye, use a find and replace
* to change 'haqiye' to the name of your theme in all the template files.
*/
// Add default posts and comments RSS feed links to head.
add_theme_support( 'automatic-feed-links' );
/*
* Let WordPress manage the document title.
* By adding theme support, we declare that this theme does not use a
* hard-coded <title> tag in the document head, and expect WordPress to
* provide it for us.
*/
add_theme_support( 'title-tag' );
/*
* Enable support for Post Thumbnails on posts and pages.
*
* @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
*/
add_theme_support( 'post-thumbnails' );
// This theme uses wp_nav_menu() in one location.
register_nav_menus(
array(
'header-menu' => esc_html__( 'Header Menu', 'haqiye' ),
'friend-link' => esc_html__('Friend Links','haqiye'),
'footer-menu' => esc_html('Footer Menu','haqiye'),
'mobile-footer' => esc_html__('Mobile footer menu','haqiye'),
)
);
/*
* Switch default core markup for search form, comment form, and comments
* to output valid HTML5.
*/
add_theme_support(
'html5',
array(
'search-form',
'comment-form',
'comment-list',
'gallery',
'caption',
'style',
'script',
)
);
// Set up the WordPress core custom background feature.
add_theme_support(
'custom-background',
apply_filters(
'haqiye_custom_background_args',
array(
'default-color' => 'ffffff',
'default-image' => '',
)
)
);
// Add theme support for selective refresh for widgets.
add_theme_support( 'customize-selective-refresh-widgets' );
/**
* Add support for core custom logo.
*
* @link https://codex.wordpress.org/Theme_Logo
*/
add_theme_support(
'custom-logo',
array(
'height' => 250,
'width' => 250,
'flex-width' => true,
'flex-height' => true,
)
);
}
add_action( 'after_setup_theme', 'haqiye_setup' );
然后你会看到外观面板那里就有了菜单选项。新建一个菜单,命名为header, 然后将左边的页面添加到菜单里面来,然后将菜单位置设置成为头部菜单(就是我们在setup里面设置的header-menu)。
然后在header.php,显示菜单的Html里面,添加显示菜单的函数(函数具体用法后面会新建文章具体讲解):
wp_nav_menu(array(
'theme_location' => 'header-menu',
'container' => false,
'menu_class' => false,
'menu_id' => false,
'before' => '<span>',
'after' => '</span>'
)
然而你发现前台的菜单样式跟Html里面的不一样,那是因为li缺少了class nli,通过钩子,我们把nli添加到li的class上:
function add_custom_menu_class($classes, $item, $args) {
if ($args->theme_location == 'header-menu') { // Replace 'primary-menu' with the name of your menu location
$classes[] = 'nli'; // Add your custom class name here
}
return $classes;
}
add_filter('nav_menu_css_class', 'add_custom_menu_class', 10, 3);
上面函数放在functions.php里面即可。