Show the Current Git Branch in the Admin Bar
Shows which Git branch and commit the site or theme is running in the admin bar for administrators, so developers always know what code is deployed on each copy.
Opens WPIDE on
Code
add_action( 'admin_bar_menu', function ( $admin_bar ) {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
foreach ( array( ABSPATH, trailingslashit( get_stylesheet_directory() ) ) as $root ) {
$head = $root . '.git/HEAD';
if ( ! is_readable( $head ) ) {
continue;
}
$ref = trim( (string) file_get_contents( $head ) );
if ( 0 === strpos( $ref, 'ref:' ) ) {
$branch = basename( trim( substr( $ref, 4 ) ) );
$file = $root . '.git/' . trim( substr( $ref, 4 ) );
$commit = is_readable( $file ) ? substr( trim( (string) file_get_contents( $file ) ), 0, 7 ) : '';
} else {
$branch = 'detached';
$commit = substr( $ref, 0, 7 );
}
$admin_bar->add_node( array(
'id' => 'wpide-git',
'parent' => 'top-secondary',
'title' => '<span class="ab-icon dashicons dashicons-randomize" style="margin-top:2px" aria-hidden="true"></span>' . esc_html( $branch . ( $commit ? ' @ ' . $commit : '' ) ),
'meta' => array( 'title' => esc_attr( 'Git repository: ' . str_replace( ABSPATH, '/', $root ) ) ),
) );
return;
}
}, 100 );
Notes
Looks for a .git folder in the site root, then in the active theme; nothing is shown when neither exists. No shell commands are run.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.