WordPress 備忘録

初歩- the_post()??

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <h1><?php the_title(); ?></h1>
  <?php endwhile; ?>

<?php else: ?>
  <p>No posts found. :(</p>
<?php endif; ?>

この一行目がもうphp初学者にはむずい。
解くとこうなる。

<?php if ( have_posts() ) : ?>
    <?php while ( have_posts() ) : ?>
        <?php the_post(); ?>
        <h1><?php the_title(); ?></h1>
    <?php endwhile; ?>
<?php endif; ?>

タグ、カテゴリ、カスタムタクソノミー

タグとカテゴリは各々管理画面から追加可能。使用はAIに聞けばいいけど一応

    <?php
      $categories = get_the_category();
      if (!empty($categories)) {
        echo '<ul class="post-categories">';
        foreach ($categories as $category) {
          echo '<li>' . esc_html($category->name) . '</li>';
        }
        echo '</ul>';
      }
      ?>
      <?php
      $post_tags = get_the_tags();
      if (!empty($post_tags)) {
        echo '<ul class="post-tags">';
        foreach ($post_tags as $tag) {
          echo '<li>' . esc_html($tag->name) . '</li>';
        }
        echo '</ul>';
      }
      ?>

カスタムタクソノミーとは、独自に作る新たな分類タイプ。
使用するにはプラグインが必要。「Custom Post Type UI」。

あわせて知っておきたいのは、「カスタム投稿」機能。投稿や固定ページとはことなる、新たに別の「投稿」を作る機能。
標準の投稿はブログ機能を持たせておいて、もう一つ商品とかよくある質問とか投稿したい場合にカスタム投稿機能を使う。
「Custom Post Type UI」でカスタム投稿もカスタムタクソノミーも設定可能。

ページ判定

条件タグというページに色々載っている。is_pageとかis_singleとか。
注意点として、functions.phpはクエリが読み込まれてデータが帰ってくる前に読み込まれるから、functions.phpで書いてもいみない。

投稿タイプ判定

get_post_type(), post_type_exists()
投稿タイプっていうのは、投稿(post)、固定ページ(page)のようなもの。

クイックタグ

<-- next page -->みたいなので、一つの投稿ページを2分割3分割とすることが可能。

サブページ

固定ページなどで、親ページを設定した子ページ(サブページ)を設定可能。

スクリプトとスタイル

functions.phpにwp_enqueue_script()またはwp_enqueue_style()を使用してスクリプトまたはスタイルを追加する。

WordPressには、jQueryなどのよく使われるライブラリは同梱されている。(/wp_includes/script-loader.phpで確認可能)
こういうのも、wp_enqueue_script("jquery")などで登録可能。

最善はこう

function add_theme_scripts() {
	wp_enqueue_style( 'style', get_stylesheet_uri() );

	wp_enqueue_style( 'slider', get_template_directory_uri() . '/css/slider.css', array(), '1.1', 'all' );

	wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array( 'jquery' ), 1.1, true );

	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}
}
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );

add_actionとは、WordPress は処理の途中に do_action('フック名') のような「差し込みポイント」がたくさんあるので、そこに自分の関数をくっつけるためのもの。
よく使われるのは、

  • init … 早い段階で設定・登録したいとき
  • wp_enqueue_scripts … スタイル・スクリプトの wp_enqueue_*
  • wp_head<head> 内に何か出したいとき(乱用は非推奨で、CSS は基本 enqueue
  • after_setup_theme … テーマのサポート宣言(add_theme_support など)