Zenn
Open5

WordPressしたい

shotakahashotakaha

PHPの基本構文

  1. <?php ?>
  2. 配列・連想配列
  3. if
  4. while
  5. foreach
  6. 三項演算子
shotakahashotakaha

PHP処理

<?php
    // PHPを使った処理
    $title = get_the_title();    // WP関数でタイトルを取得
    $content = get_the_content();    // WP関数で本文を取得
?>

<div class="container">
    <!-- 記事のタイトルを表示 -->
    <h1><?php echo esc_html( $title ); ?></h1>
   <!-- 記事の本文を表示 -->
    <p>
        <?php $content ?>
    </p>
</div>
  • PHPで処理する部分は<?phpで開始して、?>で終了する
  • ブロックとして書くことも、インラインのように書くこともできる
  • ロジックの部分(主にPHP)と表示部分(主にHTML/CSS)は、できるかぎり分割する
shotakahashotakaha

配列

<?php
$fruits = [
    'apple',
    'banana',
    'grape',
];

print_r( $fruits );
?>
  • [ ... ] で配列を作成できる
  • 以前はarray( ... )が使われていた(いまも使える)

連想配列

<?php
$fruits = [
    'red' => 'apple',
    'yellow' => 'banana',
    'purple' => 'grape',
];

print_r( $fruits )
?>
  • [ 'key' => 'value', ...]で連想配列を作成できる
  • 以前はarray( 'key' => 'value', ...)が使われていた(いまも使える)

fruits = [
    "apple",
    "banana",
    "grape"
]
print(fruits)
  • PHPの配列の書き方はPythonと同じ
  • クォートはシングルでもダブルでもどちらでもOK
    • Pythonはダブルが好まれている?
    • PHPはシングルが好まれている?
fruits = {
    "red": "apple",
    "yellow": "banana",
    "purple": "grape",
}
  • PHPの連想配列とPythonの連想配列(辞書型)は書き方がちょっと違う
shotakahashotakaha

記事を表示したい

<?php if ( have_posts() ): ?>
    <?php while ( have_posts() ) : the_post(); ?>
        <!-- 記事を表示する -->
        <article>
            <h1><?php the_title() ?></h1>
            <p><?php the_content() ?></p>
        </article>
    <?php endwhile; ?>
<?php endif; ?>
  • single.phpなど、記事を表示するテンプレート内で、よく利用されるループ処理
  • if (have_posts() ): ... endif;で、投稿の有無を確認する
  • while (have_posts()): the_post(); ... endwhile;で、投稿ごとにthe_post()して投稿データを取得
  • HTML / CSSで文書をマークアップ
  • the_title()the_content()などのWP関数で投稿データを取得&表示
ログインするとコメントできます