Add edit link to admin bar when viewing a post type archive - Cobbled Code

WordPress adds a neat ‘Edit’ link to the admin bar when you are logged in and viewing a post, page, or taxonomy. But by default there is no edit link when viewing a post type archive.

/**
 * Add edit link to admin bar when viewing a post type archive.
 *
 * @param WP_Admin_Bar $wp_admin_bar The admin bar object.
 */
function prefix_add_archive_edit_link_to_admin_bar( $wp_admin_bar ) {

	global $wp_query;

	if (
		// Not much use for the link in the admin.
		! is_admin()

		// Only on post archive pages.
		&& is_post_type_archive()

		// The post type should be showing its UI.
		&& $wp_query->queried_object->show_ui

		// And the current user should be able to edit this post type.
		&& current_user_can( $wp_query->queried_object->cap->edit_posts ) ) {

		$title = sprintf(
			_x( 'Edit %s', 'admin bar edit archive link', 'textdomain' ),
			$wp_query->queried_object->label
		);

		$wp_admin_bar->add_menu(array(
			'id'    => 'edit',
			'title' => $title,
			'href'  => admin_url( 'edit.php?post_type=' .  $wp_query->queried_object->name ),
		));
	}
}

add_action( 'admin_bar_menu', 'prefix_add_archive_edit_link_to_admin_bar', 80 );

Leave a Reply

Your email address will not be published. Required fields are marked *