KH-WEBLOG TOP > WEBメモ > WordPress > プラグイン無しでリンクカードを作る方法:WordPress

プラグイン無しでリンクカードを作る方法:WordPress

WordPressでプラグイン無しでブログカードを作る方法をメモ。

プラグインを使用する場合Pz-LinkCardが有名かと思いますが、
サイトが重くなったりでプラグインを使いたくない場合には今回ご紹介する方法をおすすめします。
方法は簡単で下記のコードをコピペで使用できます。

コーディング・WordPress化作業を代行します

functions.phpへ追加

まず、下記のコードをfunctions.phpに追加します。


// 抜粋文を取得
function ltl_get_the_excerpt($post_id){
global $post;
$post_bu = $post;
$post = get_post($post_id);
setup_postdata($post_id);
$output = get_the_excerpt();
$post = $post_bu;
return $output;
}

//ブログカード用ショートコード
function clink_scode($atts) {
extract(shortcode_atts(array(
'url'=>"",
'title'=>"",
'excerpt'=>""
),$atts));

$id = url_to_postid($url);//URLから投稿IDを取得

$no_image = 'noimageに指定したい画像パス';//アイキャッチ画像がない場合の画像を指定

//タイトルを取得
if(empty($title)){
$title = esc_html(get_the_title($id));
}
//抜粋文を取得
if(empty($excerpt)){
$excerpt = esc_html(ltl_get_the_excerpt($id));
}

//アイキャッチ画像を取得
if(has_post_thumbnail($id)) {
$img = wp_get_attachment_image_src(get_post_thumbnail_id($id),'medium');
$img_tag = "<img src='" . $img[0] . "' alt='{$title}'/>";
}else{
$img_tag ='<img src="'.$no_image.'" alt="" width="'.$img_width.'" height="'.$img_height.'" />';
}

$clink .='
<div class="linkcard">
<a href="'. $url .'">
<div class="thumb">'. $img_tag .'</div>
<div class="txt">
<div class="ctitle">'. $title .' </div>
<div class="cexcerpt">'. $excerpt .'</div>
</div>
</a>
</div>';

return $clink;
}

add_shortcode("clink", "clink_scode");

ショートコードの出力

あとは表示したい箇所に
[clink url=”ここにURL” title=”独自で設定したいタイトルがある場合は記述” excerpt=”ここに独自の抜粋文”]
で完成です。

titleやexcerptは自動取得で問題ない場合は必要ありませんので
[clink url=”ここにURL”]
で大丈夫です。

↓出力サンプル例

コーディング・WordPress化作業を代行します

WordPressのおすすめ参考書

楽天Kobo電子書籍ストア
¥3,278 (2024/04/19 19:05時点 | 楽天市場調べ)

TAGS

.htaccess ActionScript All in one seo pack Contact Form 7 CSS CSS3 EC-CUBE Flash HTML HTML5 JavaScript jQuery LightBox PHP RSS SEO WordPress アイキャッチ画像 アクセス解析 カスタムフィールド カテゴリー カラーミーショップ カート コメント ショートコード テンプレートタグ ドロップダウンメニュー パーマリンク フォーム フルスクリーン ブログカード プラグイン ページテンプレート ページナビ ページ分割 マウスイベント リダイレクト リンク リンクカード レンタルサーバー ロールオーバー 携帯サイト 条件分岐 正規表現 関連記事