How to Automatically Post Custom Field Values on Page Publish in WordPress

Home » Snippets » How to Automatically Post Custom Field Values on Page Publish in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

If you’re a WordPress user who often needs to add custom fields to your pages, you know how time-consuming and repetitive it can be to manually add them every time you publish a new page. But what if there was a way to automatically add custom fields to your pages upon publishing? In this article, we’ll explore how you can streamline your workflow by setting up a process that automatically adds custom fields to your pages whenever you hit that publish button. Say goodbye to manual data entry and hello to increased efficiency in your web development process.

					function wpturbo_save_custom_field( $post_id ) {
    if ( ! wp_is_post_revision( $post_id ) ) {
        $custom_field_value = 'Your custom field value';
        update_post_meta( $post_id, 'custom_field', $custom_field_value );
    }
}
add_action( 'publish_post', 'wpturbo_save_custom_field' );
				

The code snippet provided allows you to automatically populate a custom field with a predetermined value when a page is published in WordPress. Let’s break it down step by step to understand how it works.

The first part of the code defines a function called wpturbo_save_custom_field that takes the $post_id as a parameter. This function will be responsible for saving the custom field value.

function wpturbo_save_custom_field( $post_id ) {   

We want to perform this action only when a new post is published and not when it’s being updated, so we add a conditional statement using the wp_is_post_revision function. If the post is not a revision, the code inside the conditional statement will be executed.

if ( ! wp_is_post_revision( $post_id ) ) {   

Inside the conditional statement, we set the value of the custom field by assigning it to the variable $custom_field_value. Change 'Your custom field value' to the desired value you want to populate the custom field with.

$custom_field_value = 'Your custom field value';

To save the custom field value, we use the update_post_meta function, passing in the $post_id, the name of the custom field as the first parameter ('custom_field'), and the value as the second parameter ($custom_field_value).

update_post_meta( $post_id, 'custom_field', $custom_field_value );

Lastly, we need to hook this function into the publish_post action. This ensures that the wpturbo_save_custom_field function is executed when a post is published.

add_action( 'publish_post', 'wpturbo_save_custom_field' );

Once the code is added to your theme’s functions.php file, the custom field will automatically be populated with the specified value whenever a new post is published in WordPress.

Register an account to save your snippets or go Pro to get more features.