WordPress【twenty seventeen】標準ソーシャルリンクメニューに「はてブ(はてなブックマーク)」アイコンを実装する方法

はてなブックマーク
Pocket

WordPress【twenty seventeen】だた標準で用意されている「ソーシャルリンクメニュー」だが、日本特有のサービスである「はてブ(はてなブックマーク)」や「LINE」といったアイコンが「svg-icons.svg」に用意されていない。【twenty seventeen】の仕組みを分析するとわかるのだが「svg-icons.svg」に「はてブ」アイコンを追加するだけではページへの実装はできない。また、親テーマを直接いじらず子テーマ側で全てをオーバライドすることも出来ない仕組みとなっている。将来的にWordPress側でアイコンが準備される可能性もあることから、今回は子テーマで「ソーシャルリンクメニュー」にカスタマイズを入れることにした。まずは前回の記事である「WordPress【twenty seventeen】svgファイルの仕組みを理解し「svg-icons.svg」に「はてなブックマーク」アイコンを追加する方法、無料の「Boxy Svg」で作成する方法」を参考にして「はてブ(はてなブックマーク)」を追加したSVGファイルを作成してもらいたい。

本サイトのもので良ければコチラの「svg-child-icons」をダウンロードしてご利用ください。ZIPファイルになってますので解凍してご利用ください。

標準のソーシャルリンクメニューを有効利用するには

当初筆者は「子テーマ / assets / images / svg-icons.svg」を「はてブ」アイコン入りファイルとし、「親テーマ / inc / icon-functions.php」をカスタマイズしたものを「子テーマ / inc / icon-functions.php」へ放り込めばオーバーライドされるものだと思っていたのだが現実は違った。大きな理由は2つある。

子テーマが優先されない大きな2つの理由

  1. 「親テーマ / functions.php 」の一番下の行を見て貰いたい。下の様な記載がはずです。ここで問題なのが「get_parent_theme_file_path」。親テーマ側で親テーマ側のフォルダのPHPファイルを参照してしまっている。もうどうにもなりません。子テーマ側で全ての処理の後に書き換えも考えたのですが、もう1点どうにもならない理由があります。
    /**
    * SVG icons functions and filters.
    */
    require get_parent_theme_file_path( '/inc/icon-functions.php' );
  2. 「親テーマ / inc / icon-functions.php 」の一番最初の関数を見て貰いたい。これも「親テーマ /assets / images / svg-icons.svg 」を参照してしまっていることもあるのだが、一番決定的なのが「require_once( $svg_icons );」という定義である。これは再定義することはできない致命的な一文でした。
    
    /**
     * Add SVG definitions to the footer.
     */
    function twentyseventeen_include_svg_icons() {
    	// Define SVG sprite file.
    	$svg_icons = get_parent_theme_file_path( '/assets/images/svg-icons.svg' );
    
    	// If it exists, include it.
    	if ( file_exists( $svg_icons ) ) {
    		require_once( $svg_icons );
    	}
    }
    add_action( 'wp_footer', 'twentyseventeen_include_svg_icons', 9999 );

このような理由から子テーマから親テーマを継承やオーバーライドすることは諦めました。子テーマ側で全て作ってやれば良いのです。親テーマでやっていることを。これから説明することは難しくはありません。親テーマの関数と重複しないように気をつけながら親テーマを見習って作り直せば良いだけです

ソーシャルリンクメニュー実装方

【手順1】

「はてブ」アイコンを追加したファイルを「子テーマ /assets / images / svg-child-icons.svg 」へ配置する。別にファイル名は変えても良いですよ。本サイトではこのようにしました。

【手順2】

「子テーマ / inc / icon-child-functions.php 」を作成する。このファイルの中身は下の様になっています。ファイルの取得パスと各関数名称に「_child」を付加してます。下のコードをコピー&ペーストでもしてご自由にお使いください。

<?php
/**
* SVG icons related functions and filters
*
* @package WordPress
* @subpackage Twenty_Seventeen
* @since 1.0
*/
/**
* Add SVG definitions to the footer.
*/
function twentyseventeen_child_include_svg_icons() {
        // Define SVG sprite file.
        $svg_icons = get_theme_file_path( '/assets/images/svg-child-icons.svg' );

       // If it exists, include it.
       if ( file_exists( $svg_icons ) ) {
               require_once( $svg_icons );
       }
}
add_action( 'wp_footer', 'twentyseventeen_child_include_svg_icons', 9999 );

/**
* Return SVG markup.
*
* @param array $args {
* Parameters needed to display an SVG.
*
* @type string $icon Required SVG icon filename.
* @type string $title Optional SVG title.
* @type string $desc Optional SVG description.
* }
* @return string SVG markup.
*/
function twentyseventeen_child_get_svg( $args = array() ) {
        // Make sure $args are an array.
        if ( empty( $args ) ) {
                return __( 'Please define default parameters in the form of an array.', 'twentyseventeen' );
        }

        // Define an icon.
        if ( false === array_key_exists( 'icon', $args ) ) {
                return __( 'Please define an SVG icon filename.', 'twentyseventeen' );
        }

        // Set defaults.
        $defaults = array(
                'icon' => '',
                'title' => '',
                'desc' => '',
                'fallback' => false,
        );

        // Parse args.
        $args = wp_parse_args( $args, $defaults );

        // Set aria hidden.
        $aria_hidden = ' aria-hidden="true"';

        // Set ARIA.
        $aria_labelledby = '';

        /*
         * Twenty Seventeen doesn't use the SVG title or description attributes; non-decorative icons are described with .screen-reader-text.
         *
         * However, child themes can use the title and description to add information to non-decorative SVG icons to improve accessibility.
         *
         * Example 1 with title: <?php echo twentyseventeen_get_svg( array( 'icon' => 'arrow-right', 'title' => __( 'This is the title', 'textdomain' ) ) ); ?>
         *
         * Example 2 with title and description: <?php echo twentyseventeen_get_svg( array( 'icon' => 'arrow-right', 'title' => __( 'This is the title', 'textdomain' ), 'desc' => __( 'This is the description', 'textdomain' ) ) ); ?>
         *
         * See https://www.paciellogroup.com/blog/2013/12/using-aria-enhance-svg-accessibility/.
         */
         if ( $args['title'] ) {
                 $aria_hidden = '';
                 $unique_id = uniqid();
                 $aria_labelledby = ' aria-labelledby="title-' . $unique_id . '"';

                 if ( $args['desc'] ) {
                         $aria_labelledby = ' aria-labelledby="title-' . $unique_id . ' desc-' . $unique_id . '"';
                 }
          }

          // Begin SVG markup.
          $svg = '<svg class="icon icon-' . esc_attr( $args['icon'] ) . '"' . $aria_hidden . $aria_labelledby . ' role="img">';

          // Display the title.
          if ( $args['title'] ) {
                  $svg .= '<title id="title-' . $unique_id . '">' . esc_html( $args['title'] ) . '</title>';

                  // Display the desc only if the title is already set.
                  if ( $args['desc'] ) {
                          $svg .= '<desc id="desc-' . $unique_id . '">' . esc_html( $args['desc'] ) . '</desc>';
                  }
           }

          /*
           * Display the icon.
           *
           * The whitespace around `<use>` is intentional - it is a work around to a keyboard navigation bug in Safari 10.
           *
           * See https://core.trac.wordpress.org/ticket/38387.
           */
          $svg .= ' <use href="#icon-' . esc_html( $args['icon'] ) . '" xlink:href="#icon-' . esc_html( $args['icon'] ) . '"></use> ';

          // Add some markup to use as a fallback for browsers that do not support SVGs.
          if ( $args['fallback'] ) {
                  $svg .= '<span class="svg-fallback icon-' . esc_attr( $args['icon'] ) . '"></span>';
          }

          $svg .= '</svg>';

          return $svg;
}

/**
* Display SVG icons in social links menu.
*
* @param string $item_output The menu item output.
* @param WP_Post $item Menu item object.
* @param int $depth Depth of the menu.
* @param array $args wp_nav_menu() arguments.
* @return string $item_output The menu item output with social icon.
*/
function twentyseventeen_child_nav_menu_social_icons( $item_output, $item, $depth, $args ) {
        // Get supported social icons.
        $social_icons = twentyseventeen_social_links_icons();

        // Change SVG icon inside social links menu if there is supported URL.
        if ( 'social' === $args->theme_location ) {
                foreach ( $social_icons as $attr => $value ) {
                        if ( false !== strpos( $item_output, $attr ) ) {
                                $item_output = str_replace( $args->link_after, '</span>' . twentyseventeen_child_get_svg( array( 'icon' => esc_attr( $value ) ) ), $item_output );
                        }
                }
        }

        return $item_output;
}
add_filter( 'walker_nav_menu_start_el', 'twentyseventeen_child_nav_menu_social_icons', 10, 4 );

/**
* Add dropdown icon if menu item has children.
*
* @param string $title The menu item's title.
* @param object $item The current menu item.
* @param array $args An array of wp_nav_menu() arguments.
* @param int $depth Depth of menu item. Used for padding.
* @return string $title The menu item's title with dropdown icon.
*/
function twentyseventeen_child_dropdown_icon_to_menu_link( $title, $item, $args, $depth ) {
        if ( 'top' === $args->theme_location ) {
                foreach ( $item->classes as $value ) {
                        if ( 'menu-item-has-children' === $value || 'page_item_has_children' === $value ) {
                                $title = $title . twentyseventeen_child_get_svg( array( 'icon' => 'angle-down' ) );
                        }
                }
         }

         return $title;
}
add_filter( 'nav_menu_item_title', 'twentyseventeen_child_dropdown_icon_to_menu_link', 10, 4 );

/**
* Returns an array of supported social links (URL and icon name).
*
* @return array $social_links_icons
*/
function twentyseventeen_child_social_links_icons() {
        // Supported social links icons.
        $social_links_icons = array(
                'behance.net' => 'behance',
                'codepen.io' => 'codepen',
                'deviantart.com' => 'deviantart',
                'digg.com' => 'digg',
                'dribbble.com' => 'dribbble',
                'dropbox.com' => 'dropbox',
                'facebook.com' => 'facebook',
                'flickr.com' => 'flickr',
                'foursquare.com' => 'foursquare',
                'plus.google.com' => 'google-plus',
                'github.com' => 'github',
                'instagram.com' => 'instagram',
                'linkedin.com' => 'linkedin',
                'mailto:' => 'envelope-o',
                'medium.com' => 'medium',
                'pinterest.com' => 'pinterest-p',
                'getpocket.com' => 'get-pocket',
                'reddit.com' => 'reddit-alien',
                'skype.com' => 'skype',
                'skype:' => 'skype',
                'slideshare.net' => 'slideshare',
                'snapchat.com' => 'snapchat-ghost',
                'soundcloud.com' => 'soundcloud',
                'spotify.com' => 'spotify',
                'stumbleupon.com' => 'stumbleupon',
                'tumblr.com' => 'tumblr',
                'twitch.tv' => 'twitch',
                'twitter.com' => 'twitter',
                'vimeo.com' => 'vimeo',
                'vine.co' => 'vine',
                'vk.com' => 'vk',
                'wordpress.org' => 'wordpress',
                'wordpress.com' => 'wordpress',
                'yelp.com' => 'yelp',
                'youtube.com' => 'youtube',
                'hatena.ne.jp' => 'hatena',
         );

         /**
          * Filter Twenty Seventeen social links icons.
          *
          * @since Twenty Seventeen 1.0
          *
          * @param array $social_links_icons Array of social links icons.
          */
         return apply_filters( 'twentyseventeen_child_social_links_icons', $social_links_icons );
}

【手順3】

「子テーマ / footer.php」の下の赤字部分の関数名称を変更する。


<?php
    wp_nav_menu( array(
        'theme_location' => 'social',
        'menu_class' => 'social-links-menu',
        'depth' => 1,
        'link_before' => '<span class="screen-reader-text">',
        'link_after' => '</span>' . twentyseventeen_child_get_svg( array( 'icon' => 'chain' ) ),
    ) );
?>

これで全てカスタマイズは完了である。本サイトを参照するとわかるが、左下にソーシャルリンクアイコンが「はてなブックマーク」アイコンも含め出力されるはずである。

このようにカスタマイズしておけば、将来的にWordPressで「はてなブックマーク」が標準搭載された場合には、今回作成したファイルを削除して呼出す関数を変更してあげれば良いだけとなる。少し説明が長くなりましたが、本サイトに掲載されているコードはご自由に利用して貰って構いません。その際にはリンクでも貼っていただけると有難いです

【A8.netに登録しよう!】
◇ 広告主数・アフィリエイトサービス数日本最大級☆
◇ 登録はもちろん無料、審査なしのアフィリエイトサービス☆
◇ 使いやすいサイトNO.1
アフィリエイトならA8.net

Pocket

“WordPress【twenty seventeen】標準ソーシャルリンクメニューに「はてブ(はてなブックマーク)」アイコンを実装する方法” への4件の返信

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です