nobee

update: Last updated: 435view

WordPressでよく使うタグの取得や表示について

WordPressでよく使うタグの取得や表示について

WordPressのカスタマイズに頻繁に使うタグや関数など、まとめてみました。

テンプレートタグ

タイトルの表示は次のようになります。

<?php the_title(); ?>

the_titleを変更すればいろんな表示ができます。

投稿タイトル
the_title()
投稿本文
the_content()
投稿日
the_date()
アイキャッチ画像
the_post_thumbnail()
投稿者
the_author()
投稿URL
the_permalink()
抜粋
the_excerpt()

特定のページだけ投稿日の日付の表示を変更したい時などはこのように書きます。

<?php the_date('Y.n.j'); ?>   ⇒  2024.5.2

<?php the_date('Y年n月j日'); ?>   ⇒  2024年5月2日

<?php the_date('y年m月d日H時i分'); ?>   ⇒  24年05月02日21時00分

ただただ注意点がございまして!
the_dateでは一覧表示などで既に同じ日付が表示されないのです!!
そんな時は。

<?php the_time('y年m月d日H時i分'); ?>   ⇒  24年05月02日21時00分

the_timeを使いましょう!

投稿URLの取得

$val = get_permalink();
    

投稿URLの戻り値が変数$valに代入されます。

条件分岐タグ

トップページページだけ条件にしたい場合

if ( is_home() || is_front_page() ) :

特定の固定ページだけ条件にしたい場合

if ( is_page('スラッグ名') :

elseが入るときは

elseif ( is_page('スラッグ名')) :

特定の投稿ページだけ条件にしたい場合

if ( is_single('スラッグ名') :

elseが入るときは

elseif ( is_single('スラッグ名')) :

特定のカテゴリだけ条件にしたい場合

if ( is_category('スラッグ名') :

elseが入るときは

elseif ( is_category('スラッグ名')) :

検索結果ページだけ条件にしたい場合

if ( is_search() :

elseが入るときは

elseif ( is_search()) :

特定のカスタム投稿だけ条件にしたい場合

if ( get_post_type() === 'カスタム投稿タイプ名') :

使い方としては次のようになります。

<?php if ( is_home() || is_front_page() ) : ?>
//トップページだけの条件内容
<?php elseif ( is_page('about')) : ?>
//スラッグ名がaboutだけの条件内容
<?php elseif ( is_category('column')) : ?>
//スラッグ名がcolumnだけの条件内容
<?php elseif ( is_category('news')) : ?>
//スラッグ名がnewsだけの条件内容
<?php elseif ( is_search()) : ?>
//検索結果ページだけの条件内容
<?php else : ?>
//どの条件にもあてはまらない場合
<?php endif; ?>
    

本文があるかどうか判断したいとき

<?php $content = get_the_content();
if($content == ''): ?>
//本文がない場合の処理
<?php else : ?>
//本文がある場合の処理
<?php endif; ?>
    

サムネイルがあるかどうか判断したいとき

<?php if ( has_post_thumbnail()): ?>
  <?php the_post_thumbnail();?>
<?php endif; ?>
    

カテゴリ取得

<?php
  $category = get_the_category();
  $cat_id   = $category[0]->cat_ID; //カテゴリIDの取得
  $cat_name = $category[0]->cat_name; //カテゴリ名の取得
  $cat_slug = $category[0]->category_nicename; //カテゴリのスラッグ名の取得
?>
    

まとめておくと何より自分が便利になりました!

share

人気記事