Tag: wordpress

  • Switch WordPress Database based on Git Branch

    I’m working on a large redesign project where lots of database changes are going to take place. In order to not mix-up the current master branch with the new redesign changes, I made a new database so I can keep things separate. The only trick is to remember to change out the database in wp-config.php when I switch branches.

    That’s not going to happen. I’ll definitely forget. Regularly.

    Fortunately, you can grab the branch you’re on via php with a bit of code from user program247365 on stackoverflow.

    I took that and added a bit to choose the database I want based on the branch I’m on. You’ll need to change out the $db_name and $branch variables to match your own, then you’ll be good to go!

    // get branchname
    function config_get_git_branch() {
        // This assumes you have your .git directory at the same level as wp-config.php.
        // If you don't, then change the path to wherever your .git director is
        $stringfromfile = file('.git/HEAD', FILE_USE_INCLUDE_PATH);
    
        $firstLine = $stringfromfile[0]; //get the string from the array
    
        $explodedstring = explode("/", $firstLine, 3); //seperate out by the "/" in the string
    
        $branch = $explodedstring[2]; //get the one that is always the branch name
    
        return trim($branch);
    }
    
    // choose which db you want to use
    function config_get_db_name() {
        $branch = config_get_git_branch();
    
        // change these $db_name and and $branch strings to match
        // whatever ones you want.
        if($branch === 'child') {
            $db_name = 'child_db';
        } else {
            $db_name = 'site_db';
        }
        return $db_name;
    }
    
    // ** MySQL settings - You can get this info from your web host ** //
    /** The name of the database for WordPress */
    define('DB_NAME', config_get_db_name());
    

    Now you’ll never forgot to switch the DB out when you checkout to a new branch. Happy coding!

  • How to Detect If There’s a Featured Image on a WordPress Page or Post

    I’m redesigning the website for a Mindfulness Practice Center in New Hampshire, Morning Sun Community, and ran into an issue where I didn’t want the Title on the WordPress page to show if there was a featured image. The layout looks cleaner without the title there (although they opted to have the title appear anyways). The php code I used checks for a header image, then if there is one, do nothing. If there isn’t one, throw the title of the post in there.

    <?php
    	//Check if there is a header image
    	if ( has_post_thumbnail( $post->ID ) ) { ?>
    	<?php } else { ?>
    		<h1 class="entry-title"><?php the_title(); ?></h1>
    	<?php } ?>

    The code snippet is pretty useful anytime you want to check for a featured image and do something if there is/isn’t one.

    Have fun!