Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPB Cup
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

WordPressで投稿日: 公開する際に自動的にカスタムフィールドを追加する方法

WordPressの投稿を公開する際に自動的にカスタムフィールドを作成することは、開発者にとって強力なツールになります。

考えてみてください:特定のタイプのコンテンツを公開するたびに同じカスタムフィールドを手動で設定する代わりに、プロセス全体を自動化することができます。

WordPressサイトに新機能を追加する際、この簡単なトリックを使うことで時間を節約し、ワークフローを効率化することができます。

この投稿では、WordPressで投稿公開する際にカスタムフィールドを自動的に追加する方法を紹介する。

How to Add Custom Fields Automatically on Post Publish in WordPress

なぜカスタムフィールドを自動的に追加するのか?

カスタムフィールドを使用すると、投稿に追加情報を追加できます。この情報は、サイトに表示したり、非公開にしたり、WordPressサイトの機能を拡張するためにテーマやプラグインで使用したりすることができます。

カスタムフィールドを使う方法はたくさんあります。カスタムフィールドのヒント、トリック、ハックガイドに役立つアイデアのリストがあります。

投稿を公開するたびに、カスタムフィールドを自動的に作成したい場合があります。これは、WordPressに機能を追加して、単なるブログ以上の使い方ができるようにする場合に特に当てはまります。

ギャラリーのサイトを作るときにこの方法を使いました。私たちはギャラリーに送信された項目ごとに短いURLを保存したかったのです。そこで、各投稿が公開されたときにショートURLを保存するカスタムフィールドを自動的に作成しました。

このトリックは、WordPressを次のレベルに押し上げようとしている開発者にとって非常に便利です。

投稿日: 公開する際に自動的にカスタムフィールドを追加する

この方法では、テーマのfunctions.phpファイルにカスタム・コード・スニペットを追加します。テーマファイルを編集することは、経験の浅いユーザーにはお勧めしません。

代わりに、このチュートリアルではWPCodeプラグインの使い方を紹介します。

WPCode

WPCodeは、テーマのfunctions.phpファイルを編集することなく、WordPressにコードスニペットを簡単に追加することができます。また、すべてのコードスニペットを1つの画面で管理することができます。

WordPressにコードを追加するのが初めての場合は、WordPressでコードスニペットをコピー&ペーストする方法をご覧ください。

開始するには、無料のWPCodeプラグインをインストールし、有効化する必要があります。ヘルプが必要な場合は、WordPressプラグインのインストール方法のチュートリアルを参照してください。

注:WPCodeの無料版には、WordPressでカスタムコードを追加するために必要なすべてがあります。スケジュールスニペット、コンバージョンピクセルなど、より高度な機能を使用するには、WPCode Proにアップグレードすることができます。

プラグインを有効化すると、WordPressの管理バーに「Code Snippets」という新しいメニュー項目が追加されます。それをクリックし、次の画面で「新規追加」ボタンを押してください。

Click the Add New Button to Add Your First Custom Code Snippet in WPCode

WPCodeのスニペット・ライブラリが表示されます。

ここから「カスタムコードの追加(新規スニペット)」設定に移動し、その下にある「+カスタム・スニペットの追加」ボタンをクリックします。

Click the Add Custom Snippet button

次に、画面にポップアップ表示されるオプションの一覧から、コードタイプとして「PHP Snippet」を選択する。

Select PHP Snippet as the code type

その後、スニペットにタイトルを付け、以下のコードをコピー&ペーストして「コード・プレビュー」ボックスに入れる。

1
2
3
4
5
6
7
8
add_action('publish_page', 'add_custom_field_automatically');
add_action('publish_post', 'add_custom_field_automatically');
function add_custom_field_automatically($post_ID) {
    global $wpdb;
    if(!wp_is_post_revision($post_ID)) {
        add_post_meta($post_ID, 'field-name', 'custom value', true);
    }
}

フィールド名’と’カスタム値’は、カスタムフィールドに使用したい実際の名前と値に置き換えてください。

Paste code snippet in WPCode code box

次に、「インサーター」セクションまでスクロールダウンします。ここでは、「自動挿入」を選択したままにしておく必要があります。

Pick the insertion method for your custom code snippet

Auto Insertメソッドを使えば、スニペットは自動的に挿入され、適切な位置で実行される。

完了したら、スイッチを「Inactive」から「Active」に切り替え、「Save Snippet」ボタンをクリックします。

Save and activate your custom code snippet

スニペットを有効化すると、投稿を公開するたびにカスタムフィールドが作成されます。

このチュートリアルで、WordPressで投稿日: 公開する際にカスタムフィールドを自動的に追加する方法を学んでいただけたでしょうか。WordPressでカスタムフィールドをループの外に表示する方法や、サイトを成長させるために必須のWordPressプラグインのリストもご覧ください。

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us. Here's our editorial process.

アバター

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

The Ultimate WordPress Toolkit

Get FREE access to our toolkit - a collection of WordPress related products and resources that every professional should have!

Reader Interactions

16件のコメントLeave a Reply

  1. Sateesh Raghuwanshi

    I need to add this action for custom post type named ‘ad_system’

  2. nayan

    I want to add category Id for the post in the post_meta table. How can be the function function add_custom_field_automatically($post_ID) be twicked to accomodate that?

    Thanks

  3. chris

    Instead of adding the custom field at the time of creating the post, how do I display a custom field by default on the admin page?

    • Editorial Staff

      If you notice, the code above doesn’t have anything related to the custom post types. It only adds to Post and Page “content type”. So you would have to specify the hook for your custom post type.

      Admin

      • puanthanh

        Thanks for the reply. Can you help me out on this code.
        add_action(‘publish_page’, ‘add_custom_field_automatically’);
        add_action(‘publish_post’, ‘add_custom_field_automatically’);
        add_action( ‘save_post’, ‘add_custom_field_automatically’ );

        function add_custom_field_automatically($post_ID) {
        global $post;
        if(!wp_is_post_revision($post_ID)) {
        global $wpdb;
        $user_id = $wpdb->get_var("SELECT post_author FROM $wpdb->posts WHERE ID = $post_ID");
        $themename = $wpdb->get_var("SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = ‘themeperauthor’ AND user_id = $user_id");
        add_post_meta($post_ID, ‘themeperauthor’, $themename, true);
        }
        }
        When the user meta field is changed, I want to automatically delete the custom field value and update with the new one

  4. brian

    I’ve been working on adding some hidden custom fields on post publish/update (by preceding the field name with “_”) but for some reason I have to update the post twice before the wp_postmeta entries are written to the database.

    I’ve tried messing with the priority and experimenting with other action hooks (draft_to_publish, edit_post, etc) but it doesn’t seem to make a difference.

    Any ideas?

  5. Boba

    Thanks for including the source link :)

  6. Piet

    will this work too for custom post types?
    sth like add_action(‘publish_custom-post-typ-name’, ‘add_custom_field_automatically’);

    • Otto

      Yes, it will.

      One downside to this technique that people should be aware of is that if somebody edits a published post, this hook WILL get fired again on the edit. Therefore, you need to check for the meta before adding it, or to update it, or to do whatever makes the most sense for your use-case.

      If you only want to get your code fired off on the initial publish only, then you can use the transition_post_status hook. This hook works like this:


      add_action('transition_post_status','example',10,3);
      function example($new, $old, $post) {
      // $new is the new post status ('publish')
      // $old is the old post status ('draft')
      // $post is the complete Post Object (so use $post->ID for the ID, etc)
      }

      Then, in here you can do a check for something like this:

      if ($new == 'publish' && $old != 'publish')

      To have your code only used when the post status actually transitions to publish from whatever it was before. This hook is fired at the same time as the {$status}_{$post-type} hooks are, so the operation of them is basically the same.

  7. Vivek Parmar

    thanks for this handy tip. previously while using custom fields i have to work manually. now this will do it automatically. thanks for saving precious time of me

Leave A Reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.