[WordPress] 自作プラグイン、Twenty Twentyテーマ幅の修正、子テーマのcontent.phpをいじる – △ID11199 [2020/03/01] ID11199

はじめに

サイトの表示具合は、設定されているCSSを変更して自分好みに変更したり、自作のプラグインにCSSコードを埋め込んだり、色々と方法があるようです。CSSをいじる場合は、小テーマを作って、それを編集するようにします。子テーマを作る理由は、テーマのアップデートによって上書きされてしまうので、それを避けるためです。私も専門家ではありませんが、これからは、徐々にサイトの表示具合をカスタマイズしていきたいと思っていますが、その手法もいろいろあり、それらを学んで行こうと思います。

自作プラグイン

まだ、表示幅の埋め込みしかできていません。当サイトでしようしているTwenty Twentyテーマの投稿のデフォルト幅を、以下の手順で自作プラグインとしてインストールして、広くなるように設定できます。

  • 参考1からWordPressのTwenty Twentyテーマのデフォルトの投稿幅を広くするコードを、参考1のmy-plugin.phpの指定の箇所にコピペする
  • my-plugin.phpは、WordPressのブラインインとしてインストールできるようにパッケージされているので、ダウンロードしたファイルの組合せで、アップロードしてインストールする。
  • 以上の操作で、設定が反映される。

参考1
WordPress5.3 新デフォルトテーマ Twenty Twenty をチェックしています

https://nendeb.com/819

参考2
WordPress (自分専用)マイ・プラグインを作ろう

https://nendeb.com/1

完成したプラグインのコード

幅の修正のオリジナルは、functions.phpにグローバル変数として設定されており580px(下の「functions.php」を参照)でしたが、iPad Pro 11で閲覧して違和感のない広さに設定してみました。

その設定では、860pxになっています。以下のコードのコメントには、オリジナルの値580pxを残していますが、実際の設定コードは860pxに変更しています。

functions.php

グローバル変数 $content_width

	// Set content-width.
	global $content_width;
	if ( ! isset( $content_width ) ) {
		$content_width = 580;
	}

my-plugin.php

<?php
/*
Plugin Name: my-plugin
Plugin URI:
Description: My Plugin For WordPress.
Version: 1.0.2
Author: nendeb
Author URI: http://nendeb.com/
License: GPLv2 or later
*/


// ここからコードをいれてください。

// Start_01,WordPress Theme: Twenty Twenty の表示幅
/* コンテンツ幅は 580px と だいぶ狭いなと思うので 簡単に変更できるかテストしてみました。
公開画面と管理画面のCSS と $GLOBALS[‘content_width’] を上書きしてみます。
*/

/*
 * 公開画面での Content幅を 860px へ変更する
 * @since Twenty Twenty 1.0
 * License: GPLv2 or later
 */
function twentytwenty_org_style() {
    echo '<style>
    .section-inner.thin,
    .entry-content > *:not(.alignwide):not(.alignfull):not(.alignleft):not(.alignright):not(.is-style-wide){
        max-width: 86rem;
    }
    </style>';
}
add_action( 'wp_head', 'twentytwenty_org_style', 99 );
 
 
/*
 * 管理画面での Content幅を 860px へ変更する
 * @since Twenty Twenty 1.0
 * License: GPLv2 or later
 */
function twentytwenty_admin_style() {
    // Content幅 860 + 30 -> 860 + 0 : Admで確認した画面がUserの画面と異ならないようにした
    echo '<style>
    .wp-block {
        max-width: 860px;
    }
    .wp-block[data-align="wide"] {
        max-width: 860px;;
    }
    .wp-block[data-align="full"] {
        max-width: none;
    }
    </style>';
}
add_action( 'admin_print_styles', 'twentytwenty_admin_style', 99 );
 
 
/*
 * content_width を 860px へ変更する
 * @since Twenty Twenty 1.0
 * License: GPLv2 or later
 */
function twentytwenty_content_width() {
    // This variable is intended to be overruled from themes.
    $GLOBALS['content_width'] = 860;
}
add_action( 'after_setup_theme', 'twentytwenty_content_width', 0 );

// End_01











// ここまで


if ( ! function_exists( 'nendebcom_hide_myplugin_updateplugin' ) ) :
/*
 * サンプル
 * my-pluginの更新を非表示
 *
 * Note : https://nendeb.com/350
 */
function nendebcom_hide_myplugin_updateplugin( $data ) {
	if ( isset( $data->response['my-plugin/my-plugin.php'] ) ) {
		unset( $data->response['my-plugin/my-plugin.php'] );
	}
	return $data;
}
add_filter( 'site_option__site_transient_update_plugins', 'nendebcom_hide_myplugin_updateplugin' );
endif; // nendebcom_hide_myplugin_updateplugin





if ( ! function_exists( 'nendebcom_plugin_last_load' ) ) :
/*
 * サンプル
 * my-plugin を最後に読み込むようにする。
 * Note : https://nendeb.com/10
*/
function nendebcom_plugin_last_load() {

    $this_activeplugin  = '';
    $this_plugin        = 'my-plugin/my-plugin.php';    //最後に読み込みたいプラグイン
    $active_plugins     = get_option( 'active_plugins' );
    $new_active_plugins = array();

    foreach ( $active_plugins as $plugins ) {
        if( $plugins != $this_plugin ){
            $new_active_plugins[] = $plugins;
        }else{
            $this_activeplugin = $this_plugin;
        }
    }

    if( $this_activeplugin ){
        $new_active_plugins[] = $this_activeplugin;
    }

    if( ! empty( $new_active_plugins ) ){
        update_option( 'active_plugins' ,  $new_active_plugins );
    }
}
add_action( 'activated_plugin', 'nendebcom_plugin_last_load' );
endif; // nendebcom_plugin_last_load

子テーマのfunctions.phpをいじる

子テーマの作り方は、以下の関連記事をご参照ください。

子テーマのディレクトリ直下にある「functions.php」に以下のコードを挿入します。

functions.php

  • 子テーマ定義
  • 自動保存無効化
  • Headに(adsense)組み込み
    • AMP対応したページ/投稿には、headerにJavaScriptコードは使えません。挿入しても無効化されます。
<?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
  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')
  );
}

// 自動保存を無効にする処理
function autosave_off() {
  wp_deregister_script('autosave');
}
add_action( 'wp_print_scripts', 'autosave_off' );
// For no support to AMP, AMP do not allow insertion to Header
// 以下は、<Head>と</head>の間にGoogle Adsenseコードを挿入
// ただし、AMPでは、無秩序に挿入は許されないため、AMPを使用する場合は削除
function km_script () {
 echo '<div><script data-ad-client="ca-pub-1277399675163968" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script></div>';
}
add_action( 'amp_post_template_head', 'km_script' );
//

?>

ログインしているときに処理する

編集の最中に、投稿内容をブラウザで表示させて確認する場合、「編集」リンクを投稿の最初や最後の方に表示できると便利です。以下は、投稿の最初に表示させるカスタマイズです。同時に前後の投稿ナビゲーションも表示させます。

content.phpに、以下のコードを挿入します。

<?php if (is_user_logged_in()) : ?>

	<div>
	<?php
	if ( is_single() ) {
	
		get_template_part( 'template-parts/navigation' );
			
	}

		// 編集
		edit_post_link();

	?>
	</div>

<?php endif;?>

完成した – content.php

  • 前後の投稿へのナビゲータ
  • 投稿の編集リンクの表示

以下、完成した content.phpのコード

<?php
/**
 * The default template for displaying content
 *
 * Used for both singular and index.
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/
 *
 * @package WordPress
 * @subpackage Twenty_Twenty
 * @since 1.0.0
 */

?>

<article <?php post_class(); ?> id="post-<?php the_ID(); ?>">

	<?php

	get_template_part( 'template-parts/entry-header' );

	if ( ! is_search() ) {
		get_template_part( 'template-parts/featured-image' );
	}

	?>

	<div>
	<?php 
	// 全ページに表示 : カテゴリメニュー
	get_template_part( 'template-parts/info-course' );  
	?>
	</div>

<?php if (is_user_logged_in()) : ?>

	<div>
	<?php
	if ( is_single() ) {
	
		get_template_part( 'template-parts/navigation' );
			
	}

		// 編集
		edit_post_link();

	?>
	</div>

<?php endif;?>



	<div class="post-inner <?php echo is_page_template( 'templates/template-full-width.php' ) ? '' : 'thin'; ?> ">

		<div class="entry-content">

			<?php
			if ( is_search() || ! is_singular() && 'summary' === get_theme_mod( 'blog_content', 'full' ) ) {
				the_excerpt();
			} else {
				the_content( __( 'Continue reading', 'twentytwenty' ) );
			}
			?>

		</div><!-- .entry-content -->

	</div><!-- .post-inner -->

	<div class="section-inner">
		<?php
		wp_link_pages(
			array(
				'before'      => '<nav class="post-nav-links bg-light-background" aria-label="' . esc_attr__( 'Page', 'twentytwenty' ) . '"><span class="label">' . __( 'Pages:', 'twentytwenty' ) . '</span>',
				'after'       => '</nav>',
				'link_before' => '<span class="page-number">',
				'link_after'  => '</span>',
			)
		);

		// 編集
		edit_post_link();

		// Single bottom post meta.
		twentytwenty_the_post_meta( get_the_ID(), 'single-bottom' );

		if ( is_single() ) {

			get_template_part( 'template-parts/entry-author-bio' );

		}
		?>

	</div><!-- .section-inner -->

	<div>
	<?php
	?>
	</div>

	<?php

	// 全ページに表示 : カテゴリメニュー
	get_template_part( 'template-parts/info-course-end' );

	if ( is_single() ) {

		get_template_part( 'template-parts/navigation' );

	}

	/**
	 *  Output comments wrapper if it's a post, or if comments are open,
	 * or if there's a comment number – and check for password.
	 * */
	if ( ( is_single() || is_page() ) && ( comments_open() || get_comments_number() ) && ! post_password_required() ) {
		?>

		<div class="comments-wrapper section-inner">

			<?php comments_template(); ?>

		</div><!-- .comments-wrapper -->

		<?php
	}
	?>

</article><!-- .post -->

Font-weight

font-weightの値は、100から900まで100刻み(未確認、1刻みでも可能かもしれない)で設定できます。

  • 400 : 普通の太さ
  • 700 : bold
  • 普通文字を500すれば、見やすくななる(ブロガーさんの提案)

https://masaa.net/2018/12/28/post-181227-4/

編集履歴

2020/04/08 文言整備、ソース記載、タイトル修正
2020/05/01 文言整備
2021/02/25 追記 (「はじめに」)

関連記事(WordPress, Tag:customize)