CMB2でカスタムメタボックスを作成する方法

公開: 2016-07-25

数年前、私は投稿をクエリして、投稿がGoogleマップに書かれた場所を表示する方法を探していました。 私の調査では、CMB2とGoogleマップを使用して店舗検索機能を構築する方法についてのブログ投稿に出くわしました。 それ以来、CMB2は私のお気に入りのプラグインの1つになり、私のプロジェクトの大部分で使用されています。

まず、CMB2とは何ですか?

CMBはカスタムメタボックスの頭字語であり、プラグインページの説明によると、「CMB2は、WordPressのメタボックス、カスタムフィールド、フォームライブラリであり、心を打たれます。」 WebDevStudiosのJustinSternbergによって開発され、プラグインリポジトリに2年余り存在していました。 しかし、昨年2月、WordPressプラグインリポジトリにいる善良な人々は、CMB2をプラグインとして使用するべきではないのに、それを間違えて承認したことを認識しました。

プラグインは通常、箱から出してすぐに何かを実行できます。 それらにはいくつかの固有の機能があります。 CMB2は実際にはフレームワークです。 Sternbergがかつて説明したように、「これは、テーマやプラグインのフォームやフィールドを簡単に構築するための開発者のフレームワークです。」 実際、CMB2をインストールしても、何も起こりません。 管理ページは表示されず、管理ユーザーインターフェイスもありません。 CMB2を使用するには、コードを記述して、 functions.phpファイルに追加できる必要があります。 そのため、私はそれを「非プラグイン」プラグインと呼んでいます。

幸いなことに、プラグイン承認チームはそれをリポジトリに残すことに同意しているので、そこからダウンロードして更新し続けることができます。 あなたはここジャスティンのサイトで歴史についてのすべてを読むことができます。

CMB2の設定方法

開始するには、プラグインディレクトリからexample-functions.phpファイルを見つけて、テーマにコピーする必要があります。 テーマのルートフォルダーに直接コピーできますが、プロジェクトを適切に整理するために、 /lib//includes/などのフォルダーにコピーすることをお勧めします。 CMB2の使用方法がすでにわかっている場合は、先に進んでファイルの名前をより適切な名前に変更することをお勧めします。 たとえば、これを使用して紹介文ページのカスタムフィールドを作成する場合は、 testimonial-functions.phpという名前を付けることができます。

次に、 functions.phpファイルにrequire_onceステートメントを追加して、WordPressが新しいファイルを確実に検出するようにする必要があります。 これは次のようになります。

require_once( dirname(__FILE__) . '/lib/testimonial-functions.php');

次に、実際に掘り下げますtestimonial-functions.phpファイル(または名前を付けたもの)を開きます。 Justinは、可能なほぼすべてのタイプのフィールドの例を作成しただけでなく、ホームページ、カテゴリ、投稿IDなどでフィールドを表示するための関数も作成したことに気付くでしょう。

WordPressでJavaScriptをロードする方法

JavaScriptは、最も人気のあるコーディング言語の1つです。 Webサイトやアプリケーションを構築するときに非常に便利であり、利用できるJavaScriptライブラリやフレームワークは無数にあります...

注:この記事は、CMB2を紹介することを目的としています。 あらゆる側面の使用方法に関する完全なチュートリアルになるわけではありません。これはフレームワークであり、プログラマーを支援するために開発されたものであるため、PHPとWordPressの内部動作の基本を理解している必要があります。 管理ユーザーインターフェイスを備えたカスタムメタボックスプラグインをお探しの場合は、AdvancedCustomFieldsプラグインを確認することをお勧めします。

それでは、紹介文などの単純なもののために、いくつかのカスタムメタボックスの作成に戻りましょう。 まず、必要なフィールドの数とタイプを決定します。 簡単にするために、3つのフィールドが必要だとします。 1つは実際の紹介文用、1つは紹介文を提供する人の名前用、もう1つはその人の画像用です。

testimonial-functions.phpファイルで作業しているときに、新しい関数を登録および追加するためのセクションを見つける必要があります。 そのコードは次のようになります。

add_action( 'cmb2_admin_init', 'yourprefix_register_demo_metabox' );

次に、関数の名前をテーマとプロジェクトに関連するものに変更することをお勧めします。

add_action( 'cmb2_admin_init', 'register_testimonial_metabox' );
/**
 * Hook in and add a testimonial metabox. Can only happen on the 'cmb2_admin_init' or 'cmb2_init' hook.
 */
function register_testimonial_metabox() {

また、プレフィックスの名前を変更することをお勧めします。

// Start with an underscore to hide fields from custom fields list
$prefix = '_yourprefix_'; //note, you can use anything you'd like here, but you need to remember what you use, because you will be using it again later.

選択できるフィールドタイプはいくつかあります。 私が使用するつもりです:

'type' => 'textarea_small' // for the author field
'type'    => 'wysiwyg' // for the testimonial in case we want to include html
'type' => 'file' // for the image of the project or author

$cmb_demo->add_field( array(
	'name' => __( 'Testimonial Author', 'cmb2' ),
	'desc' => __( 'Who is the testimonial from', 'cmb2' ),
	'id'   => $prefix . 'author', //Note, I renamed this to be more appropriate
	'type' => 'textarea_small',
	) );

$cmb_demo->add_field( array(
	'name'    => __( 'Testimonial', 'cmb2' ),
	'desc'    => __( 'add the testimonial here', 'cmb2' ),
	'id'      => $prefix . 'testimonial', //Note, I renamed this to be more appropriate
	'type'    => 'wysiwyg',
	'options' => array( 'textarea_rows' => 5, ),
	) );

	$cmb_demo->add_field( array(
	'name' => __( 'Author Image', 'cmb2' ),
	'desc' => __( 'Upload an image or enter a URL.', 'cmb2' ),
	'id'   => $prefix . 'image', //Note, I renamed this to be more appropriate
	'type' => 'file',
	) );

これらの3つの新しいフィールドを新しい関数に追加する必要があるため、次のようになります。

add_action( 'cmb2_admin_init', 'register_testimonial_metabox' );
/**
 * Hook in and add a testimonial metabox. Can only happen on the 'cmb2_admin_init' or 'cmb2_init' hook.
 */
function register_testimonial_metabox() {

 // Start with an underscore to hide fields from custom fields list
    $prefix = '_yourprefix_'; //note, you can use anything you'd like here

/**
 * Start field groups here
 */

$cmb_demo->add_field( array(
	'name' => __( 'Testimonial Author', 'cmb2' ),
	'desc' => __( 'Who is the testimonial from', 'cmb2' ),
	'id'   => $prefix . 'author', //Note, I renamed this to be more appropriate
	'type' => 'textarea_small',
	) );

$cmb_demo->add_field( array(
	'name'    => __( 'Testimonial', 'cmb2' ),
	'desc'    => __( 'add the testimonial here', 'cmb2' ),
	'id'      => $prefix . 'testimonial', //Note, I renamed this to be more appropriate
	'type'    => 'wysiwyg',
	'options' => array( 'textarea_rows' => 5, ),
	) );

	$cmb_demo->add_field( array(
	'name' => __( 'Author Image', 'cmb2' ),
	'desc' => __( 'Upload an image or enter a URL.', 'cmb2' ),
	'id'   => $prefix . 'image', //Note, I renamed this to be more appropriate
	'type' => 'file',
	) );
}

以上です! 最終的なコードは次のようになります。

<?php
/**
 * Include and set up custom metaboxes and fields. (Make sure you copy this file outside the CMB2 directory)
 *
 * Be sure to replace all instances of 'yourprefix_' with your project's prefix.
 * http://nacin.com/2010/05/11/in-wordpress-prefix-everything/
 *
 * @category YourThemeOrPlugin
 * @package  Demo_CMB2
 * @license  http://www.opensource.org/licenses/gpl-license.php GPL v2.0 (or later)
 * @link     https://github.com/WebDevStudios/CMB2
 */

/**
 * Get the bootstrap! If using the plugin from wordpress.org, REMOVE THIS!
 */

if ( file_exists( dirname( __FILE__ ) . '/cmb2/init.php' ) ) {
	require_once dirname( __FILE__ ) . '/cmb2/init.php';
} elseif ( file_exists( dirname( __FILE__ ) . '/CMB2/init.php' ) ) {
	require_once dirname( __FILE__ ) . '/CMB2/init.php';
}

add_action( 'cmb2_admin_init', 'register_testimonial_metabox' );
/**
 * Hook in and add a testimonial metabox. Can only happen on the 'cmb2_admin_init' or 'cmb2_init' hook.
 */
function register_testimonial_metabox() {

 // Start with an underscore to hide fields from custom fields list
    $prefix = '_yourprefix_'; //note, you can use anything you'd like here

/**
 * Start field groups here
 */

// This first field group tells WordPress where to put the fields. In the example below, it is set to show up only on Post_ID=10

$cmb_demo = new_cmb2_box( array(
		'id'            => $prefix . 'metabox',
		'title'         => __( 'Homepage Custom Fields', 'cmb2' ),
		'object_types'  => array( 'page', ), // Post type
		'show_on'      => array( 'id' => array( 10, ) ), // Specific post IDs to display this metabox
		) );

$cmb_demo->add_field( array(
	'name' => __( 'Testimonial Author', 'cmb2' ),
	'desc' => __( 'Who is the testimonial from', 'cmb2' ),
	'id'   => $prefix . 'author', //Note, I renamed this to be more appropriate
	'type' => 'textarea_small',
	) );

$cmb_demo->add_field( array(
	'name'    => __( 'Testimonial', 'cmb2' ),
	'desc'    => __( 'add the testimonial here', 'cmb2' ),
	'id'      => $prefix . 'testimonial', //Note, I renamed this to be more appropriate
	'type'    => 'wysiwyg',
	'options' => array( 'textarea_rows' => 5, ),
	) );

	$cmb_demo->add_field( array(
	'name' => __( 'Author Image', 'cmb2' ),
	'desc' => __( 'Upload an image or enter a URL.', 'cmb2' ),
	'id'   => $prefix . 'image', //Note, I renamed this to be more appropriate
	'type' => 'file',
	) );
}

完了すると、次のようなページが表示されます。

使用方法-cmb2-例

CMB2を使用することは、オプションが本当に無限であるため、Webサイトに必要なものを正確に提供するための優れた方法です。 たとえば、CMB2を使用して、ロゴ、ソーシャルメディアサイトへのURL、またはビデオのメタボックスを含むテーマオプションページを作成できます。 クライアント用のWebサイトを構築する場合、CMB2は、クライアントがテーマのスタイルに一致するようにコンテンツをフォーマットする必要がないように、管理者をカスタマイズするのに最適です。 また、データを入力すると、HTMLとCSSにすべてのスタイルが設定されたコンテンツを表示できます。

CMB2で基本フィールドの追加をマスターしたら、繰り返し可能なフィールドグループを追加してみてください。 これらを使用すると、必要な数のコンテンツタイプを追加でき、for-eachループを使用して、スライドショーまたはカルーセルの作成を開始できます。

CMB2により、WordPressサイトを次のレベルに引き上げることができました。これで、同じことができるようになることを願っています。

次のステップ:プラグイン!

サイト開発をスピードアップする完璧なWordPressプラグインを見つけることは、コードの文字列から単一のタイプミスを見つけようとすることに少し似ています。時間がかかる場合があります。 そして最近では、さまざまなタスク用のプラグインが非常に多いため、サイトが必要とする(または必要としない)機能と、それを効率的に提供するプラグインを正確に特定するのは難しい場合があります。

開発者に最も推奨されるプラグインのリストについては、この電子ブックをダウンロードしてください。