Shortcode to display the title of the post the user is editing

Description/Instructions

When the user edits a post you can’t use dynamic tags to display the title of the post they are editing, so I created this shortcode that can be used on the edit/create post page.

In my setup, I have a post type that some users can only edit and I hide the title field so they cannot edit the title, therefore I want to display what post they are currently editing.

Instructions

To display the title of the post you are editing use shortcode:

[edit_post_shortcode display="title"]

To display the last time that post was updated use shortcode:

[edit_post_shortcode display="last-update"]

 

function edit_post_shortcode($atts) {
$attributes = shortcode_atts(array('display' => '',), $atts);
$post_id = isset($_GET['post_id']) ? intval($_GET['post_id']) : 0;
if (!$post_id) {
return 'No valid post ID provided.';
}
$post = get_post($post_id);
if (!$post) {
return 'Post not found.';
}
switch ($attributes['display']) {
case 'title':
returnesc_html($post->post_title);
case 'last-updated':
returndate_i18n('j F Y', strtotime($post->post_modified));
default:
return 'Invalid display option specified.';
}
}
add_shortcode('edit-post', 'edit_post_shortcode');
  • PHP
Copy Code

Let's Chat About this Snippet