忘れがちなコード集
テンプレート内でショートコードの呼び出し
<?php
echo do_shortcode('[ショートコードの文字列]');
?>
the_contentの文字数制限とhtmlタグ削除
<?php
$pattern=array("/\[.+?\]/","/[\r|\n]+/","/\[|\]+/","/ /");
$replace=array('','','','');
$result=preg_replace($pattern, $replace, $post-> post_content);
if(mb_strlen(strip_tags($result)) > 45){
$content= apply_filters('the_content',mb_substr(strip_tags($result),0,45));
echo $content.'…';
}else{
echo apply_filters('the_content',$result);
}
?>
カスタムフィールドで取得したYouTubeのURLからIDだけを取得
※自動再生などwp_oembed_get()では付けられないパラメータをつける時に便利
<?php
$url = 'カスタムフィールドで取得したyoutube url';
preg_match('/\?v=([^&]+)/',$url,$match);
$youtube_id = $match
;
?>
//autoplay=1が自動再生
<iframe src="https://www.youtube.com/embed/<?php echo $youtube_id; ?>?autoplay=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
カスタムフィールドで画像のIDを取得して、サイズを変更して表示する
<?php
$img_id = カスタムフィールドの値;
$img = wp_get_attachment_image_src($img_id,'large');
?>
<img src="<?php echo $img[0]; ?>" alt="">
<?php //返り値
[0] => url
=> width
=> height
=> 真偽値: リサイズされいている場合は true、元のサイズの場合は false
?>
WP_Term_Query(ターム一覧情報を簡単に取得できる関数)
※WordPress ver4.6〜
<?php
$args = array(
'taxonomy' => 'pref', // タクソノミースタッグを指定
'order' => 'DESC',
);
$the_query = new WP_Term_Query($args);
foreach($the_query->get_terms() as $term):
$c_name = $term->name;
echo $c_name;
endforeach;
?>
<!-- 取得データサンプル -->
[term_id] => 77
[name] => 鹿児島県
[slug] => kagoshima
[term_group] => 0
[term_taxonomy_id] => 77
[taxonomy] => pref
[description] =>
[parent] => 0
[count] => 32
[filter] => raw
[term_order] => 4
<!-- ここまで -->
wp_query() タームまで指定
<?php
$args = array(
'post_type' => 'post_name',
'posts_per_page' => 3,
'tax_query' => array(
array(
'taxonomy' => 'post_tax_name',
'field' => 'slug',
'terms' => array(
'term_name',
),
),
)
);
$my_query = new WP_Query( $args );
while ( $my_query->have_posts() ) : $my_query->the_post();
?>
<!-- ループ内容 -->
<?php
endwhile;
wp_reset_postdata();
?>
ループを使わずに特定のカスタムフィールドを取得する方法
<?php
// $post->ID部分は任意のIDを指定できる
$c_field = get_post_meta($post->ID,'カスタムフィールド名', true);
echo $c_field;
?>
パラメータがなければリダイレクト
例)ページID17にアクセスする際、「flg」のパラメータがなければTOPへリダイレクト
<?php
if(is_page('17')){
if(!$_GET['flg']){
wp_redirect( '/' );
exit;
}
}
?>
たまに使う忘れがちな条件分岐
has_term()特定のタームに属する
<?php
// 特定のタームに属する時
if(has_term('ターム名','タクソノミー名')){
echo 'ダミーテキスト';
}
// 特定のターム以外
if(!has_term('ターム名','タクソノミー名')){
echo 'ダミーテキスト';
}
?>
データベースを直接参照する方法
global $wpdb;
$result = $wpdb->get_results( 'SELECT テーブルカラム名(複数の場合はカンマで繋ぐ) FROM 取得したいテーブル名; ' );
print_r( $result );