Skip to content

Instantly share code, notes, and snippets.

@devlifeX
Created May 12, 2024 19:34
Show Gist options
  • Save devlifeX/3874f9f38026c9a5bdc6c4fb5cc32d94 to your computer and use it in GitHub Desktop.
Save devlifeX/3874f9f38026c9a5bdc6c4fb5cc32d94 to your computer and use it in GitHub Desktop.
Add rotitr
<?php
/*
Plugin Name: Rotitr
Description: rotiter add new custom field to post area
Version: 1.0.0
Author: dariushvesal
Author URI: https://vesal.blog
*/
// don't load directly
if (!defined('ABSPATH')) die();
class Rotitr {
function __construct() {
add_action('add_meta_boxes', [$this, 'custom_post_field_meta_box']);
add_action('save_post', [$this, 'save_custom_post_field_meta_box_data']);
add_action('rotitr', [$this, 'render_rotitr']);
}
/**
* add <?php do_action('rotitr'); ?> to single.php to render field
*/
function render_rotitr() {
$custom_field_value = get_post_meta(get_the_ID(), '_custom_post_field', true);
if (!empty($custom_field_value)) {
// Output the custom field value before the <h1> tag
echo '<div class="rotitr"><p>' . esc_html($custom_field_value) . '</p></div>';
}
}
function custom_post_field_meta_box() {
add_meta_box(
'custom_post_field_meta_box', // Unique ID
'رو تیتر', // Box title
[$this, 'custom_post_field_meta_box_callback'], // Content callback function
'post', // Post type
'normal', // Context
'high' // Priority
);
}
function custom_post_field_meta_box_callback($post) {
// Add a nonce field so we can check for it later
wp_nonce_field('custom_post_field_meta_box', 'custom_post_field_meta_box_nonce');
// Get the current value of the custom field
$custom_field_value = get_post_meta($post->ID, '_custom_post_field', true);
// Output the field
?>
<label for="custom_post_field">روتیتر:</label>
<input type="text" id="custom_post_field" name="custom_post_field" value="<?php echo esc_attr($custom_field_value); ?>" style="width: 100%;" />
<?php
}
function save_custom_post_field_meta_box_data($post_id) {
// Check if our nonce is set.
if (!isset($_POST['custom_post_field_meta_box_nonce'])) {
return;
}
// Verify that the nonce is valid.
if (!wp_verify_nonce($_POST['custom_post_field_meta_box_nonce'], 'custom_post_field_meta_box')) {
return;
}
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check the user's permissions.
if (isset($_POST['post_type']) && 'post' == $_POST['post_type']) {
if (!current_user_can('edit_post', $post_id)) {
return;
}
}
// Sanitize user input.
$custom_field_value = isset($_POST['custom_post_field']) ? sanitize_text_field($_POST['custom_post_field']) : '';
// Update the meta field in the database.
update_post_meta($post_id, '_custom_post_field', $custom_field_value);
}
}
new Rotitr();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment