Automatically add Custom Fields When Post Published

What is WordPress Custom field ?

WordPress custom fields are a feature that allows you to add additional metadata or information to your WordPress posts, pages, or custom post types. They provide a way to store and display extra data alongside your content, beyond the default fields provided by WordPress (such as title, content, author, date, etc.).

Custom fields two main components:

Name: This is the identifier or name of the custom field. It’s used to reference the field when retrieving or displaying its value. For example, you might use a key like “author_bio” to store the author’s biography.

Value: This is the actual data or content associated with the custom field. It could be text, numbers, URLs, dates, or even complex data structures like arrays or serialized data.

How Automatically add Custom Fields When Post Published

Open and add the code blow Appearance >>Theme >> functions.php

/* 
How Automatically add Custom Fields When Post Published
 */

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, 'name', 'value', true);
    }
}

Now published post and check value added.

How to show custom field value in theme ? 

1.Simple Display

<?
php $data  = get_post_meta( get_the_ID(), 'value_name', true );
echo '$data'; 
?>

 2.Check if the custom field value exists

<?php
// Check if the custom field value exists
$custom_field_value = get_post_meta(get_the_ID(), 'custom_field_key', true);
if (!empty($custom_field_value)) {
    // Display the custom field value
    echo 'Custom Field Value: ' . esc_html($custom_field_value) . '';
}
?>

3.display alternative data if a custom field is empty,

If you want to display alternative data if a custom field is empty, you can use conditional statements to check if the custom field value exists. If it does, you display the custom field value; otherwise, you display the alternative data. Here’s how you can do it:

<?php
// Retrieve the custom field value
$custom_field_value = get_post_meta(get_the_ID(), 'custom_field_key', true);

// Check if the custom field value is empty
if (!empty($custom_field_value)) {
    // Display the custom field value
    echo 'Custom Field Value: ' . esc_html($custom_field_value) . '';
} else {
    // Display alternative data if the custom field value is empty
    echo 'Alternative Data: This is the alternative data when the custom field value is empty.';
}
?>

 

Leave a Reply

Your email address will not be published. Required fields are marked *