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

functions.phpへ
// 内部リンクをショートコードで指定する
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');
記事へ
[get_postlink id=記事ID postpage=postやpage、カスタム投稿のスラッグ]
[get_postlink id=postid slug=slug postpage=post anchorlink=aaa anchortext=あああ]



