Certains thèmes, dont mon petit chouchou (Twenty-Twenty-four) n’offrent pas la possibilité nativement d’ajouter une Meta Description à mes pages et posts.
Le plugin ci-dessous y remédie.
Télécharger le plugin
Ce plugin ajoute un champ, en bas de l’éditeur, vous permettant de renseigner la meta description de votre publication (post et page).
Contenu du plugin
<?php
/*
Plugin Name: Simple Meta Description Plugin
Description: Add a meta description field in gutenberg editor.
Version: 1.0
Author: Arnaud OGM
*/
// Add a custom meta description field
function mdp_add_meta_description_box() {
add_meta_box(
'mdp_meta_description', // unique ID
'Meta Description', // Meta box title
'mdp_meta_description_box_html', // Callback function
['post', 'page'], // Type of publications
'normal', // Context (normal, side, advanced)
'high' // Priority
);
}
add_action('add_meta_boxes', 'mdp_add_meta_description_box', 10, 2);
// Function to display the custom field in the editor
function mdp_meta_description_box_html($post) {
$meta_description = get_post_meta($post->ID, '_mdp_meta_description', true);
?>
<label for="mdp_meta_description">Meta Description:</label>
<textarea id="mdp_meta_description" name="mdp_meta_description" rows="3" style="width:100%;"><?php echo esc_textarea($meta_description); ?></textarea>
<?php
}
// Functipon to save the meta description
function mdp_save_meta_description($post_id) {
if (array_key_exists('mdp_meta_description', $_POST)) {
update_post_meta(
$post_id,
'_mdp_meta_description',
sanitize_text_field($_POST['mdp_meta_description'])
);
}
}
add_action('save_post', 'mdp_save_meta_description');
// Function to add the meta description to the head section
function mdp_add_meta_description_to_head() {
if (is_single() || is_page()) {
global $post;
$meta_description = get_post_meta($post->ID, '_mdp_meta_description', true);
if ($meta_description) {
echo '<meta name="description" content="' . esc_attr($meta_description) . '">' . "\n";
}
}
}
add_action('wp_head', 'mdp_add_meta_description_to_head');
Laisser un commentaire