WORDPRESSの投稿を Custom Post Type UI と Advanced Custom Fields の組み合わせで便利にする

Custom Post Type UIをインストールして設定。

acf01a

続いてAdvanced Custom Fieldsをインストールして各種項目を設定。

acf02a

「投稿タイプ」を選んで先ほど作った"event"を選択。

acf03a

すると、”イベント登録”から新規追加した時のみカスタムフィールドが表示される。

アーカイブページ等で文字数を制限する

<?php echo mb_substr(strip_tags($post-> post_content),0,60) . '...'; ?>

上記コードは60文字制限。

ループで表示させる場合は以下のようなコードで。

<?php
$wp_query = new WP_Query();
$param = array(
'posts_per_page' => '-1', //表示件数。-1なら全件表示
'post_type' => 'event', //カスタム投稿タイプの名称を入れる
'post_status' => 'publish', //取得するステータス。publishなら一般公開のもののみ
'orderby' => 'date', //ID順に並び替え
'order' => 'ASC'
);
$wp_query->query($param);
if($wp_query->have_posts()): while($wp_query->have_posts()) : $wp_query->the_post();
?></p>
<pre><code>&lt;?php
$img = get_field('event-photo');
$imgurl = wp_get_attachment_image_src($img, 320, 200);
if($imgurl){ ?&gt;
&lt;div class=&quot;event-photo&quot;&gt;
    &lt;img src=&quot;&lt;?php echo $imgurl[0]; ?&gt;&quot; alt=&quot;&quot;&gt;
&lt;/div&gt;
&lt;!-- /.event-photo --&gt;
&lt;?php } ?&gt;
&lt;div class=&quot;event-detail green&quot;&gt;
    &lt;h3 class=&quot;event-title&quot;&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt;
    &lt;h4 class=&quot;event-date&quot;&gt; 
        &lt;?php
        //デイトピッカー
        $datepicker = get_field('event-date'); 
        if($datepicker){ 
        ?&gt;
        &lt;?php echo $datepicker; ?&gt;
        &lt;?php } ?&gt;
        &lt;?php
        //曜日の出力
            $week = get_field('event-dayoftheweek');
            if($week){ 
        ?&gt;
        &lt;? echo $week; ?&gt;
        &lt;? } ?&gt;
    &lt;/h4&gt;
    &lt;h5 class=&quot;event-time&quot;&gt;
        OPEN / START
        &lt;?php the_field('event-dayoftheweek'); ?&gt;
    &lt;/h5&gt;
    &lt;p class=&quot;event-text&quot;&gt;&lt;?php echo mb_substr(strip_tags($post-&gt; post_content),0,60) . '...'; ?&gt;&lt;/p&gt;
    &lt;div class=&quot;more-btn&quot;&gt;
        &lt;a href=&quot;&lt;?php the_permalink(); ?&gt;&quot;&gt;more&lt;/a&gt;
    &lt;/div&gt;
    &lt;!-- /.more-btn --&gt;
&lt;/div&gt;
&lt;!-- /.event-detail --&gt;</code></pre>
<p><?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else: ?>
<!-- 投稿が無い場合の処理 -->
<?php endif; ?>

WORDPRESS

Posted by bistro