LoginSignup
1
0

More than 3 years have passed since last update.

[ WordPress ] リンクなしでカテゴリを出力する

Last updated at Posted at 2020-09-08

WordPressの投稿記事に紐づいたカテゴリを出力するには、通常 <?php the_category(); ?> を使いますが、その場合リンクもつきます。

このリンクをなくしたいと思いました。実装方法は、<?php get_the_category(); ?> を用いて一旦配列に格納して、ループで表示させました。また、複数のカテゴリを表示させる際セパレート(,)をつけて見やすくしましたが、最後のカテゴリが出力された際セパレータがつかないよう条件分岐もさせています。

loop.php
<?php
  $categories = get_the_category();
  $length = count($categories);
  $i = 0;

  foreach($categories as $cat){
    $i++;
    if($length == $i){
      echo $cat->cat_name;
    }else{
      echo $cat->cat_name . ', ';
    }
  }
?>

implode を使う

上記を投稿したところ、下記のように implode を使えばシンプルに実装できるとコメントを頂戴しました。

technote-space様、ありがとうございました!

loop.php
<?php
 $categories = get_the_category();
 echo implode(', ', array_map(function($cat) { return $cat->cat_name; }, $categories));
?>

参考URL

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0