WordPressのfunction.phpで常用するコード②(表示編)
2016.07.04
投稿ID取得
function.php
function postID() {
global $id;
echo $id;
}
表示用
<?php postID(); ?>
固定ページ スラッグ取得
function.php
function page_slug(){
global $post;
echo $post->post_name;
}
表示用
<?php page_slug(); ?>
親ページ(最上位)スラッグ取得
function.php
function ps_get_root_page( $cur_post, $cnt = 0 ) {
if ( $cnt > 100 ) { return false; }
$cnt++;
if ( $cur_post->post_parent == 0 ) {
$root_page = $cur_post;
} else {
$root_page = ps_get_root_page( get_post( $cur_post->post_parent ), $cnt );
}
return $root_page;
}
function parent_slug() {
global $post;
$root_slug = ps_get_root_page( $post );
$root_slug = $root_slug->post_name;
echo $root_slug;
}
表示用
<?php parent_slug(); ?>
カテゴリ スラッグ取得
function.php
function cat_slug(){
$cat = get_the_category();
$catslug = $cat[0]->slug;
echo $catslug;
}
表示用
<?php cat_slug(); ?>
カテゴリ名取得(リンクなし)
function.php
function cat_name(){
$cat = get_the_category();
$catname = $cat[0]->cat_name;
echo $catname;
}
表示用
<?php cat_name(); ?>
タグ名取得(リンクなし)
function.php
function tag_name(){
$posttags = get_the_tags();
$count = count($posttags);
$loop = 0;
if ($posttags) {
foreach ($posttags as $tag) {
$loop++;
if ($count == $loop){
echo $tag->name . '';
} else {
echo $tag->name . '/';
}
}
}
}
表示用
<?php tag_name(); ?>
ターム名取得(リンクなし)
function.php
function get_the_term_list_nolink( $id = 0, $taxonomy, $before = '', $sep = '', $after = '' ) {
$terms = get_the_terms( $id, $taxonomy );
if (is_wp_error( $terms ))
return $terms;
if (empty( $terms ))
return false;
foreach ( $terms as $term ) {
$term_names[] = $term->name ;
}
return $before . join( $sep, $term_names ) . $after;
}
表示用
<?php echo get_the_term_list_nolink($post->ID,'タクソノミー名'); ?>
NEWマーク表示(30日間)
function.php
function new_icon(){
$days = 30;
$today = date_i18n('U');
$entry = get_the_time('U');
$kiji = date('U',($today - $entry)) / 86400 ;
if( $days > $kiji ){
echo '<span class="new">NEW</span>';
}}
表示用
<?php new_icon(); ?>