how to add custom field in plugin wordpress

To add a custom field in a WordPress plugin, follow these steps:

Define the field: Determine what kind of field you want to add, and define its parameters. For example, you might want to add a text input field for a custom URL, with a label of "Custom URL". You'll need to decide on the field's name, ID, label, default value, and any other necessary attributes.

Add the field to the plugin: In your plugin code, create a function that adds the custom field. You can use the add_meta_box() function to create a custom metabox, which will contain your custom field. Here's an example:

function myplugin_add_custom_field() {
    add_meta_box(
        'myplugin_custom_url',
        'Custom URL',
        'myplugin_render_custom_url',
        'post',
        'normal',
        'default'
    );
}

function myplugin_render_custom_url($post) {
    $custom_url = get_post_meta($post->ID, '_myplugin_custom_url', true);
    ?>
    <label for="myplugin_custom_url">Custom URL</label>
    <input type="text" name="myplugin_custom_url" id="myplugin_custom_url" value="<?php echo esc_attr($custom_url); ?>">
    <?php
}
add_action('add_meta_boxes', 'myplugin_add_custom_field');

This code creates a metabox with the ID myplugin_custom_url, a title of "Custom URL", and a callback function of myplugin_render_custom_url. The myplugin_render_custom_url function displays the custom field, which is a text input field with a name of myplugin_custom_url. This function also retrieves any existing custom URL value for the current post, and populates the field with that value.

Save the field value: When the post is saved, you'll need to save the value of your custom field. You can use the save_post hook to do this. Here's an example:

function myplugin_save_custom_field($post_id) {
    if (isset($_POST['myplugin_custom_url'])) {
        update_post_meta($post_id, '_myplugin_custom_url', sanitize_text_field($_POST['myplugin_custom_url']));
    }
}
add_action('save_post', 'myplugin_save_custom_field');

This code uses the update_post_meta() function to save the value of the custom field to the post's metadata. The field's value is retrieved from $_POST, and sanitized using the sanitize_text_field() function.

 Your plugin now has a custom field that can be used to store and display additional information for posts.

.

No comments:

Post a Comment

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...