WPの記事内で自サイトのリンクをショートコードで呼び出す

functions.phpへ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | // 内部リンクをショートコードで指定する function shortcodeFunc ( $arg ) { extract ( shortcode_atts ( array ( 'id' => 0, 'slug' => '' , 'postpage' => 'post' , 'anchorlink' => '' , 'anchortext' => '' , ), $arg ) ); $html = "" ; $post_object = "" ; if ( $slug ) { $post_object = get_page_by_path ( $slug , OBJECT, $postpage ); } elseif ( $id != 0) { $post_object = get_post ( $id ); } if ( $post_object ) { if ( $anchorlink ) { $anchorlink = "#" . $anchorlink ; } if ( $anchortext ) { $anchortext = "/" . $anchortext ; } $link = get_permalink ( $post_object -> ID) . $anchorlink ; $linktxt = $post_object -> post_title . $anchortext ; $thumb = wp_get_attachment_url( get_post_thumbnail_id( $id )); // サムネイルの設定をする場合 $nothumb = "noimg.jpg" ; // サムネイルがない場合の画像を設定する場合 if ( $thumb ) { $thumb_url = $thumb ; } else { $thumb_url = $nothumb ; } // カスタム投稿のタクソノミーを取得する場合 news_cat など if ( $terms = get_the_terms( $id , 'タクソノミー1' )) { foreach ( $terms as $term ) { $term_tag = esc_html( $term ->name); } } if ( $terms = get_the_terms( $id , 'タクソノミー2' )) { foreach ( $terms as $term ) { $term_tag = esc_html( $term ->name); } } // 日付の取得をする場合 $Y = get_the_date( 'Y' ); $m = get_the_date( 'm' ); $d = get_the_date( 'd' ); $week = get_the_date( 'D' ); $html = "<a href=\"{$link}\">" ; $html .= "<img class=\"img\" src=\"{$thumb_url}\" alt=\"{$linktxt}\">" ; $html .= "{$linktxt}" ; $html .= "<span class=\"category\">{$term_tag}</span><time datetime=\"{$Y}-{$m}-{$d}\" class=\"date\">{$Y}.{$m}.{$d}</time>" ; $html .= "</a>" ; } return $html ; } add_shortcode( 'get_postlink' , 'shortcodeFunc' ); |
記事へ
1 | [get_postlink id=記事ID postpage=postやpage、カスタム投稿のスラッグ] |
1 | [get_postlink id=postid slug=slug postpage=post anchorlink=aaa anchortext=あああ] |