wordpress自定义类名能够帮助开发者实现更加灵活的UI布局,因为很多东西只有后端才清楚,让后端直接控制比前端实现更方便。本文使用<body>
标签的类名来做简单介绍,使用时可以举一反三。
先来个简单的判断登录
复制
//https://www.daimadog.org/9999.html //WordPress添加自定义CSS类名 add_filter( 'body_class', 'dmd_add_body_class' ); function dmd_add_body_class( $classes ) { if ( !is_user_logged_in() ) { // 用户没有登录 $classes[] = 'not-logged-in'; // 自定义类名 } else { // 用户已登录 $classes[] = 'logged-in'; // 自定义类名 } return $classes; }
来个比较常用的
复制
//https://www.daimadog.org/9999.html //WordPress添加自定义CSS类名 function dmd_custom_body_class( $classes ) { $include = array ( // 设备/浏览器类 (https://codex.wordpress.org/Global_Variables) 'is-iphone' => $GLOBALS['is_iphone'], 'is-chrome' => $GLOBALS['is_chrome'], 'is-safari' => $GLOBALS['is_safari'], 'is-ns4' => $GLOBALS['is_NS4'], 'is-opera' => $GLOBALS['is_opera'], 'is-mac-ie' => $GLOBALS['is_macIE'], 'is-win-ie' => $GLOBALS['is_winIE'], 'is-gecko' => $GLOBALS['is_gecko'], 'is-lynx' => $GLOBALS['is_lynx'], 'is-ie' => $GLOBALS['is_IE'], 'is-edge' => $GLOBALS['is_edge'], // WP Query (WordPress默认已包含下面的类名) 'is-archive' => is_archive(), 'is-post_type_archive' => is_post_type_archive(), 'is-attachment' => is_attachment(), 'is-author' => is_author(), 'is-category' => is_category(), 'is-tag' => is_tag(), 'is-tax' => is_tax(), 'is-date' => is_date(), 'is-day' => is_day(), 'is-feed' => is_feed(), 'is-comment-feed' => is_comment_feed(), 'is-front-page' => is_front_page(), 'is-home' => is_home(), 'is-privacy-policy' => is_privacy_policy(), 'is-month' => is_month(), 'is-page' => is_page(), 'is-paged' => is_paged(), 'is-preview' => is_preview(), 'is-robots' => is_robots(), 'is-search' => is_search(), 'is-single' => is_single(), 'is-singular' => is_singular(), 'is-time' => is_time(), 'is-trackback' => is_trackback(), 'is-year' => is_year(), 'is-404' => is_404(), 'is-embed' => is_embed(), // 手机端 'is-mobile' => wp_is_mobile(), 'is-desktop' => ! wp_is_mobile(), // Common 'has-blocks' => function_exists( 'has_blocks' ) && has_blocks(), ); // 侧边栏 foreach ( $GLOBALS['wp_registered_sidebars'] as $sidebar ) { $include[ "is-sidebar-{$sidebar['id']}" ] = is_active_sidebar( $sidebar['id'] ); } // 添加类名 foreach ( $include as $class => $do_include ) { if ( $do_include ) $classes[ $class ] = $class; } // 返回类名 return $classes; } add_filter( 'body_class', 'dmd_custom_body_class' );
删除不需要的类名
从 body_class
数组中删除某个类名,将 class-to-remove
修改为你需要的类名即可
复制
//https://www.daimadog.org/9999.html //WordPress添加自定义CSS类名 add_filter( 'body_class', 'dmd_remove_body_class' ); function dmd_remove_body_class( $classes ) { if ( isset( $classes['class-to-remove'] ) ) { unset( $classes['class-to-remove'] ); } return $classes; }
评论 (0)