Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.