見出し画像

【保存版】function phpを使いこなす〜美しいブログカードの作成方法

WordPressの自動更新完了通知をオフにする方法

通知は極限までオフにする。

これは人生を豊かに過ごすために必須のことになります。

WordPressでは通知をオフにするプラグインなどもありますが、これもまた、プラグインを極限まで減らすというのはWordPress運用において非常に重要なことであります。

function phpに以下のコードをペーストすることで、プラグインの自動更新を有効化した際に有効化完了通知がこなくなります。

// 自動更新の完了メールを無効にする
add_filter('auto_plugin_update_send_email', '__return_false');
add_filter('auto_theme_update_send_email', '__return_false');

JavaScriptの読み込み設定

WordPressにてJavaScriptを読み込ませる必要がある場合は、function phpに以下のコードを記述しましょう。

<?php
// スクリプトとスタイルを読み込む関数を定義
function custom_enqueue_scripts() {
    // jQueryを読み込む(必要に応じて)
    wp_enqueue_script('jquery');

    // カスタムスクリプトをテーマのディレクトリから読み込む
    wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom-script.js', array('jquery'), null, true);
}

// アクションフックを使用してスクリプトとスタイルを読み込む
add_action('wp_enqueue_scripts', 'custom_enqueue_scripts');
?>

WordPressでは、テーマやプラグインのスクリプトやスタイルシートを正しく読み込むために、wp_enqueue_script や wp_enqueue_style 関数を使用します。これにより、スクリプトやスタイルシートが正しい順序で、そして必要な依存関係と共に読み込まれるように管理されます。

関数名 説明 custom_enqueue_scripts 関数 この関数は、カスタムスクリプトを読み込むための関数です。 wp_enqueue_script 関数 第一引数 スクリプトのハンドル名(custom-script)。 第二引数 スクリプトのURL(テーマディレクトリの js/custom-script.js)。 第三引数 依存関係の配列(この例では jQuery)。 第四引数 スクリプトのバージョン(省略可能)。 第五引数 スクリプトをフッターに読み込むかどうかのフラグ(true でフッターに読み込み)。 add_action 関数 説明 この関数は、特定のタイミングでカスタム関数を実行するために使用されます。この場合、wp_enqueue_scripts アクションフックを使用して、テーマやプラグインのスクリプトとスタイルを正しく読み込むタイミングで custom_enqueue_scripts 関数を実行します。

これはCSSでも同様です。

CSSファイルの読み込み設定

子テーマを使用している場合は以下のコードをfunction phpに記述してください。

子テーマの functions.php ファイルに以下のコードを追加します。これにより、親テーマと子テーマのスタイルシートが正しく読み込まれます。

<?php
function my_theme_enqueue_styles() {
    $parent_style = 'parent-style'; // 親テーマのスタイルのハンドル名(例:'neve-style')

    wp_enqueue_style($parent_style, get_template_directory_uri() . '/style.css');
    wp_enqueue_style('child-style',
        get_stylesheet_directory_uri() . '/style.css',
        array($parent_style),
        wp_get_theme()->get('Version')
    );
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_styles');
?>

子テーマを使用していない場合

親テーマの functions.php ファイルに以下のコードを追加します。

これにより、テーマのスタイルシートが正しく読み込まれます。

<?php
function my_theme_enqueue_styles() {
    wp_enqueue_style('my-style', get_stylesheet_uri());
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_styles');
?>

美しいブログカードを作る

[nlink url="https://kotaroasahina.com/2024/06/12/proof-that-matter-does-not-exist/"]

内部リンクで美しいブログカードを作りたいと思ったことはありませんか?

WordPress標準の機能でもアドレスを貼れば自動で作成はしてくれますが、やはり美しくなかったりしますし、デザインが限定されてしまってカードのサイズなどの微調整をしたくてもなかなか融通が効かないと言ったことが起こります。

function phpのプログラミングで、自動でサムネイルを読み込み、ブログカードを生成してくれるショートコードを作成して、ブログ制作を加速化させていきましょう。

function phpへの記述

//ブログカード用コード
// 記事ID
function ltl_get_the_excerpt($post_id){
global $post;
$post_bu = $post;
$post = get_post($post_id);
setup_postdata($post_id);
$output = get_post_meta($post_id,'_yoast_wpseo_metadesc',true);//YoastSEOの場合
$post = $post_bu;
return $output;
}

//ショートコード
function nlink_scode($atts) {
extract(shortcode_atts(array(
'url'=>"",
'title'=>"",
'excerpt'=>""
),$atts));

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

$no_image = '';//アイキャッチ画像がない記事に使う画像URL

//記事タイトルを取得
if(empty($title)){
$title = esc_html(get_the_title($id));
}
//descriptionを取得
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.'" />';
}

$nlink .=' <div>
<a class="card-link longcard-link" href="'. $url .'" title="'.$title.'" target="_blank" rel="noopener">
<span class="longcard-img">'. $img_tag .'</span>
<span class="blogcard-content blogcard-text">
<span class="blogcard-title">'. $title .' </span>
<span class="blog-card-excerpt-long">'. $excerpt .'</span>
</span></a></div>';

return $nlink;
}

add_shortcode("nlink", "nlink_scode");

筆者はYoastSEOを使用していますので、YoastSEO用のコードを貼っています。

他のSEO対策ツールを使用している場合は

$output = get_post_meta($post_id,'_yoast_wpseo_metadesc',true);//YoastSEOの場合

この部分を書き換えてください。

//AllinOneSEOを使っている場合
$output = get_post_custom()['_aioseo_description'][0];//AllinOneSEOの場合

//YoastSEOを使っている場合
$output = get_post_meta($post_id,'_yoast_wpseo_metadesc',true);//YoastSEOの場合

//どっちも使っていない場合
$output = get_the_excerpt();

エラーが出る場合

Warning: Undefined variable $nlink in /home/あなたの環境名/public_html/wp-content/themes/あなたの使用しているテーマ/functions.php on line 1258

こういうエラーが出る場合があります。

その場合は修正案としてこちらのコードを使用してください。

//ブログカード用コード
// 記事IDを指定してdescriptionを取得
function ltl_get_the_excerpt($post_id) {
    global $post;
    $post_bu = $post;
    $post = get_post($post_id);
    setup_postdata($post_id);
    $output = get_post_meta($post_id, '_yoast_wpseo_metadesc', true); // YoastSEOの場合
    $post = $post_bu;
    return $output;
}

//ショートコード
function nlink_scode($atts) {
    extract(shortcode_atts(array(
        'url' => "",
        'title' => "",
        'excerpt' => ""
    ), $atts));

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

    $no_image = ''; // アイキャッチ画像がない記事に使う画像URL

    // 記事タイトルを取得
    if (empty($title)) {
        $title = esc_html(get_the_title($id));
    }

    // descriptionを取得
    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='" . esc_url($img[0]) . "' alt='" . esc_attr($title) . "' />";
    } else {
        $img_tag = '<img src="' . esc_url($no_image) . '" alt="" width="' . esc_attr($img_width) . '" height="' . esc_attr($img_height) . '" />';
    }

    // $nlink変数を初期化
    $nlink = '';

    // カードのHTMLを生成
    $nlink .= '<div>
    <a class="card-link longcard-link" href="' . esc_url($url) . '" title="' . esc_attr($title) . '" target="_blank" rel="noopener">
        <span class="longcard-img">' . $img_tag . '</span>
        <span class="blogcard-content blogcard-text">
            <span class="blogcard-title">' . esc_html($title) . ' </span>
            <span class="blog-card-excerpt-long">' . esc_html($excerpt) . '</span>
        </span>
    </a>
</div>';

    return $nlink;
}

add_shortcode("nlink", "nlink_scode");

各種SEO対策ツール用は上記と同様です。

CSSで微調整

/* ブログカード シンプルデザイン*/
.blog-card-long {
	margin: 0 0 1.8rem;
}
.card-link {
  display: block;
  overflow: hidden;
  max-width: 400px;
  width: 100%;
  padding: 0;
  border-radius: 3px;
  background: #fff ;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.25);
  color: #555 ;
  font-weight: bold;
  text-decoration: none !important;
  position: relative;
}
.card-link:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.25);
  color: #888 ;
  text-decoration: none;
  transform: translateY(-2px);
}
.blog-card-label-long{
	z-index: 1;
	display: inline-block;
    position: absolute;
	background-color: #f99f48 ;
    top: 10px;
	left: 10px;
	max-width: 120px;
	height: 25px;
	padding: 0 0.5rem;
    color: #fff ;
    font-size: .8rem;
    font-weight: 700;
    text-align: center;
    line-height: 25px;
    transform-origin: 50% 50%;
    animation: animScale 3.5s ease-out;
}

.card-link .blogcard-text {
  display: block;
  padding: 15px 13px;
  line-height: 1.6;
}
.card-link img {
  width: 100%;
}
.longcard-link {
  margin-bottom: 1.5em;
  box-shadow: 0 1px 5px 0 rgba(0, 0, 0, 0.25);
}
.longcard-link img {
  padding: 10px 10px 0;
}
.longcard-img{
	position: relative;
}
.blogcard-title {
	font-size: 1em;
	font-weight: bold;
	line-height: 1.9;
	display: -webkit-box;
    -webkit-box-orient: vertical;
	-webkit-line-clamp: 3;
    overflow: hidden;
    text-overflow: ellipsis;
}
.blog-card-excerpt-long {
	padding-top: .8em;
    font-size: .8em;
    line-height: 1.4;
	font-weight: normal;
    opacity: .8;
	color: #333 ;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
    text-overflow: ellipsis;
}
@media only screen and (min-width: 481px) {
	.card-link {
    	display: inline-block;
    	max-width: 310px;
    	margin-right: 10px;
 	}
	.longcard-link {
    	max-width: 100%;
    	display: table;
  	}
  	.longcard-img,
  	.card-link.longcard-link .blogcard-content {
    display: table-cell;
    vertical-align: middle;
  }
  .longcard-img {
    width: 45%;
  }
  .blogcard-content {
    width: 60%;
  }
  .longcard-img img {
    width: 100%;
    padding: 10px;
  }
}
@media screen and (max-width: 959px){
	.blog-card-excerpt-long {
		display: none;
	}
}

こちらをCSSファイルとして貼り付けてあなたのサイトにぴったり合うよう微調整してみてください。

ショートコード

あとはショートコードを貼るだけ。

[nlink url="ここにあなたのサイトのURLリンクを貼る"]

これで自動的に美しいブログカードの完成です。

WordPressの管理画面カスタマイズ

WordPressの管理画面をカスタマイズして、特定の機能を追加したり、不要なメニュー項目を削除したりできます。

: 不要な管理メニューを削除する

<?php
// 不要な管理メニューを削除する関数
function remove_menus() {
    remove_menu_page('edit-comments.php'); // コメントメニューを削除
}
add_action('admin_menu', 'remove_menus');
?>

この記事が気に入ったらサポートをしてみませんか?