Search for the Article

Easy Way to Add Custom Fields in WordPress Without Plugins

Add the following code to your theme's functions.php file to create a new custom field for the service subtitle:

function add_custom_service_subtitle_meta_box() {
    add_meta_box(
        'custom_service_subtitle',
        'Custom Service Subtitle',
        'render_custom_service_subtitle_meta_box',
        'service',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'add_custom_service_subtitle_meta_box');

function render_custom_service_subtitle_meta_box($post) {
    wp_nonce_field('custom_service_subtitle_nonce', 'custom_service_subtitle_nonce');
    $value = get_post_meta($post->ID, '_custom_service_subtitle', true);

    echo '';
}

function save_custom_service_subtitle($post_id) {
    if (!isset($_POST['custom_service_subtitle_nonce']) || !wp_verify_nonce($_POST['custom_service_subtitle_nonce'], 'custom_service_subtitle_nonce')) {
        return;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    if (isset($_POST['custom_service_subtitle'])) {
        update_post_meta($post_id, '_custom_service_subtitle', sanitize_text_field($_POST['custom_service_subtitle']));
    }
}
add_action('save_post', 'save_custom_service_subtitle');



Integrating Custom Field into Template:

I have a single.php Now, let's modify your single-service.php template to display the custom subtitle if available:


<p>
    <?php
    $custom_subtitle = get_post_meta(get_the_ID(), '_custom_service_subtitle', true);
    
    if ($custom_subtitle !== '') {
        echo htmlspecialchars_decode(esc_attr($custom_subtitle));
    } else {
        if (isset($zebizz_redux_demo['service_details_subtitle']) && $zebizz_redux_demo['service_details_subtitle'] != '') {
            echo htmlspecialchars_decode(esc_attr($zebizz_redux_demo['service_details_subtitle']));
        } else {
            echo esc_html__('Build strong & impressive websites using our premade templates', 'zebizz');
        }
    }
    ?>
</p>