【问题标题】:How to replace default wordpress navbar link text with font awesome icons?如何用字体真棒图标替换默认的wordpress导航栏链接文本?
【发布时间】:2021-04-19 01:27:49
【问题描述】:

所以我对 WP 很陌生,虽然我对 WP 导航栏有一些经验,但这是相当独特的。我正在尝试在 wp 生成的导航中注入很棒的字体图标。

基本上,当我在 wp 中创建菜单时:<?php wp_nav_menu( array( 'theme_location' => 'header-menu' ) ); ?>

WP 会为我生成:

<div class="menu-main-menu-container">
    <ul id="menu-main-menu" class="menu">
        <li id="menu-item-15" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-home current-menu-item page_item page-item-7 current_page_item menu-item-15">
            <a href="localhost_link/frontpage" aria-current="page">Home</a>
        </li>

        <li id="menu-item-14" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-14">
            <a href="localhost_link/blog/">Listen</a>
        </li>
    </ul>
</div>

有没有办法使用 ACF 或 wp_admin 或其他地方的东西来用 2 个不同的字体真棒图标替换链接文本(特别是上面示例中的“home”和“listen”)?

像这样:

<li id="menu-item-15" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-home current-menu-item page_item page-item-7 current_page_item menu-item-15">
    <a href="localhost_link/frontpage" aria-current="page"><i class="fas fa-play-circle"></i></a>
</li>

<li id="menu-item-14" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-14">
    <a href="localhost_link/blog/"><i class="fas fa-play-circle"></i></a>
</li>

注意:我不能(除非有人有更好的方法)每个链接都使用 fas fa-play-circle 类(就像在 wp_admin 菜单编辑器中一样),因为这会将它放在锚点上, 没问题,除了我已经在锚元素上使用了 :before 和 2 样式的 :before 伪不一起玩。

另外,我想要一个图标的功能(颜色、悬停等),所以也不用使用 css 背景。

甚至不确定这是否可能,但我希望如此!提前致谢!

【问题讨论】:

    标签: css wordpress wordpress-theming navbar


    【解决方案1】:

    您可以使用preg_replace。简而言之,我们定义一个匹配的$search参数,然后我们用我们想要的替换它。

    在这里我们将搜索&gt;Home&lt;&gt;Listen&lt;

    <?php
    /**
    * do_action( 'wp_loaded' )
    * This hook is fired once WP, all plugins, and the theme are fully loaded and instantiated.
    * @link https://developer.wordpress.org/reference/hooks/wp_loaded/
    */
    add_action( 'wp_loaded', function() {
      function wp_custom_fontawesome_nav( $subject ) {
        if( ! is_admin() ) {
          $search = [
            '/>Home</', // ... >Home< with the brackets, to be sure to target the right Home word
            '/>Listen</', // ... etc.
            // ... etc.
          ];
          $replace = [
            '><i class="fas fa-play-circle"></i><', // ... Our replacement for Home
            '><i class="fas fa-drum"></i><', // ... Our replacement for Listen
            // ... etc.
          ];
          $subject = preg_replace( $search, $replace, $subject );
          return $subject;
        };
      };
      ob_start( 'wp_custom_fontawesome_nav' );
    } ); ?>
    

    将其放在您的 function.php 文件中的某个位置。


    了解详情

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      • 2021-11-07
      • 2019-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多