WP Scripts

From GLMWiki
Jump to: navigation, search

Setup the Gaslight Plugins for a wordpress site

# setupWordpressPlugins.sh
#!/bin/sh
# Setup the Gaslight Plugins for a wordpress site

STARTPWD=${PWD}
cd $(wp plugin path)
 
for plugin in "Gaslightify" "glm-client-info" "glm-blocks" "glm-support-form" "GlmPrototypes"
do
    git clone "git@cvs2:WP-Plugins/$plugin.git"
    wp plugin activate $plugin
done
 
sudo chmod -R g+rw .
find . -type d -perm /g=x ! -perm /g=s -exec sudo chmod g+s '{}' \;

Setting up all the wordpress default plugins for site

#!/bin/sh
# Setup default plugins from wordpress
# requires wp-cli

echo "Installing Default Wordpress Plugins"
for plugin in "wp-media-category-management" "printfriendly" "tinymce-advanced" "nextgen-gallery" "nextgen-gallery-custom-fields" "slideshow-jquery-image-gallery" "user-role-editor" "wordpress-importer" "breadcrumb-navxt" "advanced-excerpt" "cms-tree-page-view" "wordpress-seo" "restricted-site-access" "mainwp-child" "login-lockdown"
do
    wp plugin install $plugin --activate
done

Setting up the Glm Associate Plugins

#!/bin/sh
# Script to update all member plugins

for plugin in "glm-member-db" "glm-member-db-contacts" "glm-member-db-coupons" "glm-member-db-events" "glm-member-db-packaging" "glm-member-db-social"
do
    git clone git@cvs2:WP-Plugins/$plugin
done

Update Member Plugins

#!/bin/sh
# Script to update all member plugins
WP_PLUGIN_HOME='/var/www/localhost/htdocs/wp-content/plugins'
 
cd $WP_PLUGIN_HOME
 
for plugin in "glm-member-db" "glm-member-db-contacts" "glm-member-db-packaging"
do
    cd $plugin
    git co develop
    git pull --rebase
    cd $WP_PLUGIN_HOME
done

Install all Default GLM and Member DB Plugins on any server

#!/bin/bash
## Setup the Gaslight Member DB Plugins for a wordpress site
## This script will:
## - work regardless of which server you're on
## - ask whether to install the default GLM plugins
## - ask whether to install the GLM Member DB plugins
## - allow a quick install 
## - use a configurable settings file
## - probably catch any common mistake
## - easily allow future plugin or server additions or changes

## Variable initialization
installed=""
notInstalled=""
alreadyInstalled=""
devBranch="n"
siteName=""
host=${HOSTNAME}
startDir=${PWD}
instruction=""
export TOP_PID=$$
stopScript=false
stopHost="n"
settingsFile="${HOME}/.glmscriptsettings.cfg"
wordpressHome=""
branchUsed="Master"
fullInstall=false

## Check whether we have an existing settings file, otherwise create one
if [ -r $settingsFile ]; then
    printf "\nReading $settingsFile \n"
    source $settingsFile
    newSettings=false
    wordpressHome=$cfgWordpressHome
    fullInstall=$cfgFullInstall
else
    printf "\nSettings file not found. Creating $settingsFile."
    touch $settingsFile
    printf "## This is the auto-generated settings file for the GLM Plugin script\n## You can set the option cfgFullInstall=true to do an automatic full install\ncfgFullInstall=false " >> $settingsFile
    newSettings=true
fi

## Called to properly exit the script with an error message
killMe() {
    printf "\nHalting script. ${1} \n"
    cd $startDir
    stopScript=true
}

## Try to CD to the given directory, and ask whether to use Develop
branchSetting() {
    printf "\nWould you like all plugins to automatically check out the DEVELOP branch? Y/n: "
    read devBranch
    if [ "$devBranch" = "n" ] || [ "$devBranch" = "N" ]; then
        printf "\nLeaving all plugins at MASTER branch."
    else
        branchUsed="Develop"
        devBranch="y"
    fi
}

## Determine the plugins directory based on the host, ask if unknown
getPluginHome() {
    read siteName
    validHome=false

    ## Get or set the valid Wordpress home dependent on the Host
    case "$host" in
        "dev55")
            printf "\nIt looks like we're on ${host}"
            newWordpressHome="/var/www/server"
            siteName="${siteName}.gaslightmedia.com"
          ;;
        "angelia")
            printf "\nIt looks like we're on ${host}"
            newWordpressHome="/var/www/server"
          ;;
        *)
            printf "\nSeems we're either on Localhost or a server I'm not programmed for, \nwhich as far as I can see is called $HOSTNAME.\nProceeding accordingly if you press anything but N now:"
            read stopHost
            if [ "${stopHost}" = "n" ] || [ "${stopHost}" = "N" ]; then
                killMe "Given: ${stopHost}"
                return
            fi
            newWordpressHome="invalidWordpressHome"
          ;;
 esac

    ## Pass if settings-given dir is valid, otherwise if default dir is valid
    if [ -d "$wordpressHome" ]; then
        printf "\nUsing WP sites directory set in $settingsFile"
        validHome=true
    elif [ -d "$newWordpressHome" ]; then
        wordpressHome=$newWordpressHome
        validHome=true
    fi

    ## Keep asking for a valid WP directory until getting an existing dir
    while [ "${validHome}" != true ]
    do
        printf "\nPlease enter the directory your Wordpress sites are installed in (like /var/www/server/): "
        read wordpressHome
        if [ -d "${wordpressHome}" ]; then
            validHome=true
        else
            printf "\nCannot access the given Wordpress directory."
        fi
    done

    ## Set the plugin home
    pluginHome="${wordpressHome}/${siteName}/web/wp-content/plugins/"

    ## Insert the new wordpressHome into the settingsfile
    if [ "$newSettings" = true ] || [ "${cfgWordpressHome}" = "" ]; then
        printf "\nStoring directory $wordpressHome in your $settingsFile"
        sed -i "/cfgWordpressHome=.*/d" $settingsFile
        printf "\ncfgWordpressHome=\"${wordpressHome}\"" >> $settingsFile
    fi

    if [ -d "$pluginHome" ]; then
        cd $pluginHome
        printf "\nUsing plugin directory: $pluginHome"
    else
        killMe "\nCannot find the plugin directory for the given site. Please rerun the script and try again.\nGiven: ${pluginHome}\n"
        return
    fi

    ## Find out what GIT branch to use if script isn't killed beforehand
    branchSetting
}

## Ask the sitename question dependent on the Hostname
initialization() {
    case "$host" in
      "dev55")
        printf "\nWhat site are we installing for? Enter ONLY the sitename \n(the part that goes between 'www.' and '.com', and before '.gaslightmedia.com'): "
         ;;
      "angelia")
        printf "\nWhat site are we installing for? Enter BOTH the sitename and TLD \n(everything after 'www.' including '.com'): "
         ;;
      *)
        printf "\nWhat site are we installing for? Enter ONLY the sitename\n(What the website's folder is called in your wordpress installation): "
         ;;
    esac
    getPluginHome
}

## Try to git clone the plugins if not already existent, set to develop if needed. 
##  Needs to be passed an array of strings as plugin names
installPlugins() {
    if [ -z "$1" ]; then
        printf "\nEmpty array encountered. Something must be quite wrong."
        return
    fi
    pluginArray="$@"
    for plugin in "${pluginArray[@]}"
    do
        failed=""
        duplicate=false
        if [ -d "$plugin" ]; then
            printf "\n${plugin} is already installed. Skipping."
            alreadyInstalled="$alreadyInstalled $plugin\n"
        else
            if [ "${plugin}" != "glm-member-db" ] && [ "$installOption" != "a" ] && [ "$installOption" != "A" ] && [ "$fullInstall" != true ]; then
                printf "\nDo you want to install the plugin [$plugin]? y/N: "
                read answerVar
            else
                answerVar="y"
            fi
            if [ "$answerVar" == "y" ] || [ "$answerVar" == "Y" ]; then
                printf "\nAttempting to clone [$plugin] \n"
               if git clone "git@cvs2:WP-Plugins/$plugin.git"
                then
                    installed="$installed $plugin\n"
                    if [ "$devBranch" != "n" ] && [ "$devBranch" != "N" ]; then
                        cd $plugin
                        git checkout develop
                        git pull --rebase
                        cd ..
                    fi
                else
                    failed="\nTried and failed to clone $plugin"
                fi
            else
                failed="Did not install [${plugin}]\n"
            fi
            if [ "${failed}" != "" ]; then
                if [ "${plugin}" == "glm-member-db" ]; then
                    failed="${failed}\n WARNING, without the Member DB the additional plugins will NOT work"
                fi
                printf "${failed}"
                notInstalled="$notInstalled $plugin\n"
            fi
        fi
    done
}

## Display a list of plugins installed, already installed, and/or not installed.
finalization() {
    if [ "$installed" = "" ]; then
        installed=" (none)\n"
    else
        printf "\n\nSetting permissions for the installed plugins.\n"
        sudo chmod -R g+rw .
        find . -type d -perm /g=x ! -perm /g=s -exec sudo chmod g+s '{}' \;
    fi
    printf "\n\n~===============================================~"
    printf "\n    Script Complete!"
    printf "\n~===============================================~"
    printf "\nInstalled the following plugins: \n$installed"
    if [ "$alreadyInstalled" != "" ]; then
        printf "\nThe following plugins were already installed:\n$alreadyInstalled"
    fi
    if [ "$notInstalled" != "" ]; then
        printf "\nDid not install the following plugins:\n$notInstalled"
    fi
    printf "\n\nReturn to start directory? Y/n: "
    read returnVar
    if [ "$returnVar" != "n" ] && [ "$returnVar" != "N" ]; then
        cd $startDir
    fi
}

## Program Starts Here
initialization
if [ "${stopScript}" = true ]; then
    return
fi

## Report
printf "\n\nHost name: $host"
printf "\nPlugin home: ${pluginHome}"
if [ "$siteName" != "" ]; then
    printf "\nSitename: $siteName"
fi
printf "\nGit branch: $branchUsed"

## These two installation sections function so very similarly, there must be a more efficient way to do this..
## Installing the default GLM plugins.
if "${fullInstall}";then
    installOption="a"
else
    printf "\n\nWould you like to install the default GLM plugins? Y/n/a: "
    read installOption
fi
if [ "${installOption}" != "N" ] && [ "${installOption}" != "n" ]; then
    pluginArray=("Gaslightify" "glm-client-info" "glm-blocks" "glm-support-form" "GlmPrototypes")
    installPlugins ${pluginArray[@]}
fi

## Installing the GLM Member DB plugins
if "${fullInstall}";then
    installOption="a"
else
    printf "\n\nWould you like to install the GLM Member DB plugins? Y/n/a: "
    read installOption
fi
if [ "${installOption}" != "N" ] && [ "${installOption}" != "n" ]; then
    pluginArray=("glm-member-db" "glm-member-db-packaging" "glm-member-db-contacts" "glm-member-db-social" "glm-member-db-events")
    installPlugins ${pluginArray[@]}
fi


finalization

Checkout a git repo without .git directory

mkdir glm-member-db-coupons
cd glm-member-db-coupons
{
    git archive --format=tar --remote=git@cvs2:WP-Plugins/glm-member-db-sample.git master | tar -xf -
    sudo chmod -R g+rw .
    find . -type d -perm /g=x ! -perm /g=s -exec sudo chmod g+s '{}' \;
}

Grabbing a list of MYSQL tables to make a drop script

SELECT CONCAT('DROP TABLE ', TABLE_SCHEMA, '.', TABLE_NAME, ';') 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME LIKE '\glm_23_members_glm_members_%' 
AND TABLE_SCHEMA = 'worddb' 
INTO OUTFILE '/tmp/drop';

GIT Functions & Aliases - recommended

Place this whole thing in your .bashrc. This will make it a lot easier to start new hotfixes (githot) and gives access to some more convenient aliases to widely-used, verbose commands.

##########################
# Git functions and aliases
##########################

## Function used by newGitHotfix() below to determine newest tag
function newGitTag() {
    # Get latest version number
    VERSION=`git describe --abbrev=0 --tags`
    # Remove the first character (v) which we auto-prepend
    VERSION=${VERSION#?}
    #replace . with space so it can split into an array
    VERSION_BITS=(${VERSION//./ })

    #get number parts and increase the last one by 1
    VNUM1=${VERSION_BITS[0]}
    VNUM2=${VERSION_BITS[1]}
    VNUM3=${VERSION_BITS[2]}
    VNUM3=$((VNUM3+1))

    #create new tag
    NEW_TAG="$VNUM1.$VNUM2.$VNUM3"
    echo "$NEW_TAG"
}

## Function used in conjunction with githot alias below
function newGitHotfix() {
# Check whether git exists by existence of .git folder
 if [ -d .git ]; then
    NEW_GIT_TAG=$(newGitTag)

    # See whether the local repo is clean. if not, do a stash first (doesn't drop it)
    if git diff-files --quiet --ignore-submodules --;then
      NEW_HOTFIX_LINE="git flow hotfix start $NEW_GIT_TAG;sed -i 's/Version:.*/Version: $NEW_GIT_TAG/' style.css;git add style.css;git commit style.css -m\"Theme version number bump\""
    else
      NEW_HOTFIX_LINE="git stash save prehotfix;git flow hotfix start $NEW_GIT_TAG;sed -i 's/Version:.*/Version: $NEW_GIT_TAG/' style.css;git add style.css;git commit style.css -m\"Theme version number bump\";git stash apply stash^{/prehotfix}"
    fi
    echo "eval $NEW_HOTFIX_LINE"
  else
    echo "echo Not a git repository. Aborting."
  fi
}

## Finds latest tag, increments the final number by 1, creates a hotfix on new tag num
##   does a stash if needed, updates styles.css with the new version tag
alias githot='$(newGitHotfix)'

alias githotf="git flow hotfix finish"
alias githots="git flow hotfix start"
alias gitpat="git push --all;git push --tags"
alias gitpall="git push --all"
alias gitptag="git push --tags"
alias glt='git describe --abbrev=0'

## Used in conjunction with gitrefresh alias below
function gitRefresh() {
 #Check whether we're in a git repository
 if [ -d .git ]; then
    #Check whether the local repo is clean. If not, also do git stashes
    if git diff-files --quiet --ignore-submodules --;then
       REFRESH_LINE='git checkout master;git pull origin master;git checkout develop;git pull origin develop'
    else
       REFRESH_LINE='git checkout master;git stash;git pull origin master;git stash pop;git checkout develop;git stash;git pull origin develop;git stash pop'
    fi
    echo "eval $REFRESH_LINE"
 else
    echo "echo Not a git repository. Aborting"
 fi

}

## Does a checkout and pull on origin and develop, stashes existing changes if needed
##   Not the most safe command if you have unstaged changes in non-develop or non-master branch
alias gitrefresh='$(gitRefresh)'

Finding out quickly which sites have a certain plugin installed

In the /var/www/server/ directory..
find */web/wp-content/plugins/ -type d -name "<plugin_name>"
e.g.:
find */web/wp-content/plugins/ -type d -name "all-in-one-event-calendar-frontend-submissions"

Pass variables between template files

Add this function to functions.php


/**
 * Like get_template_part() put lets you pass args to the template file
 * Args are available in the tempalte as $template_args array
 * @param string filepart
 * @param mixed wp_args style argument list
 */
function hm_get_template_part( $file, $template_args = array(), $cache_args = array() ) {
    $template_args = wp_parse_args( $template_args );
    $cache_args = wp_parse_args( $cache_args );
    if ( $cache_args ) {
        foreach ( $template_args as $key => $value ) {
            if ( is_scalar( $value ) || is_array( $value ) ) {
                $cache_args[$key] = $value;
            } else if ( is_object( $value ) && method_exists( $value, 'get_id' ) ) {
                $cache_args[$key] = call_user_method( 'get_id', $value );
            }
        }
        if ( ( $cache = wp_cache_get( $file, serialize( $cache_args ) ) ) !== false ) {
            if ( ! empty( $template_args['return'] ) )
                return $cache;
            echo $cache;
            return;
        }
    }
    $file_handle = $file;
    do_action( 'start_operation', 'hm_template_part::' . $file_handle );
    if ( file_exists( get_stylesheet_directory() . '/' . $file . '.php' ) )
        $file = get_stylesheet_directory() . '/' . $file . '.php';
    elseif ( file_exists( get_template_directory() . '/' . $file . '.php' ) )
        $file = get_template_directory() . '/' . $file . '.php';
    ob_start();
    $return = require( $file );
    $data = ob_get_clean();
    do_action( 'end_operation', 'hm_template_part::' . $file_handle );
    if ( $cache_args ) {
        wp_cache_set( $file, $data, serialize( $cache_args ), 3600 );
    }
    if ( ! empty( $template_args['return'] ) )
        if ( $return === false )
            return false;
        else
            return $data;
    echo $data;
}
-------------------------
Then call the template function in the template you want to set a variable like so..

 <?php hm_get_template_part( 'parts/template_file_here', [ 'name' => 'value' ] ); ?>

--------------------------
Access the variable in another template you want by calling:
     $template_args['name']; // to get the value

List templates currently in use on a site

Add the following to your functions.php. It will create a page at the bottom of the admin menu called "Templates Used" which lists all the templates currently in use on a site. This page can only be accessed by users with the capability of manage_options, so it is safe to leave on a site upon go-live. Additional post types can easily be added as needed using list_templates_by_type( 'my_post_type' ).

function templates_used() {
    add_menu_page(
        __( 'Templates Used', 'textdomain' ),
        'Templates Used',
        'manage_options',
        'templates-used.php',
        'list_templates_used',
        plugins_url( '' ),
        999
    );
}
add_action( 'admin_menu', 'templates_used' );

function list_templates_used( ) {
    global $post;
    echo "<br><b><h1>Templates Used</h1></b>";
    list_templates_by_type( 'page' );
    list_templates_by_type( 'post' );
    //list_templates_by_type( 'custom-post-type' );
}

function list_templates_by_type( $type = 'page' ) {
    
    $args = array( 'post_type' => $type, 'posts_per_page' => -1 );
    $posts = get_posts( $args );
    $count = 0;
    
    $output = '';
    $output .= '<br><h3>\''. $type .'\' List</h3>';
    
    foreach ($posts as $post) {
        setup_postdata( $post );
        if ( get_page_template_slug( $post->ID ) ) {
            if ( $count == 0 ) {
                $output .= ' <span>Every '. $type .' not listed below has template "Default".</span></b></br><br>';
                $output .= ' <table style="border-collapse: collapse;">';
                $output .= ' <tr><th>ID</th><th>Name</th><th>Slug</th><th>Template</th></tr>';
            }
            $count++;
            $output .= '<tr style="background-color: white;">';
            $output .= '<td style="border: 1px solid black;padding: 4px;">' . $post->ID . '</td>';
            $output .= '<td style="border: 1px solid black;padding: 4px;">' . $post->post_title . '</td>';
            $output .= '<td style="border: 1px solid black;padding: 4px;">' . $post->post_name . '</td>';
            $output .= '<td style="border: 1px solid black;padding: 4px;">' . get_page_template_slug( $post->ID ) . '</td>';
            $output .= '</tr>';
        }

    }
    $output .= '</tr>';
    $output .= '</table>';
    
    if ( $count == 0 ) {
        $output .= '<span> Either there are no posts with type "' . $type . '", or none of them have custom templates set (and have the Default template). </span>';
    }
    
    
    wp_reset_postdata();
    echo $output;
}

Create a database on localhost

#!/bin/sh
# Creates mysql database
# script ask for credentials

clear

echo "Database Name: "
read -e dbname

echo "Database User: "
read -e dbuser

echo "Database Password: "
read -s dbpass

echo "MySQL admin password required."

MYSQL=`which mysql`

Q1="CREATE DATABASE IF NOT EXISTS $dbname;"
Q2="GRANT USAGE ON *.* TO $dbuser@localhost IDENTIFIED BY '$dbpass';"
Q3="GRANT ALL PRIVILEGES ON $dbname.* TO $dbuser@localhost;"
Q4="FLUSH PRIVILEGES;"

SQL="${Q1}${Q2}${Q3}${Q4}"

$MYSQL -uroot -p -e "$SQL"

Local Stuff

Clone, set nvm, npm install, bower update, git flow init!

## Usage: getwptheme <reponame>
## Throw this in your .bashrc file, or alternatively make it a script to run globally
## Head into your wp-content/themes dir, and run it with 'getwptheme migcsa' or 'getwptheme TrueNorthGolf'
## It will still initialize a bad repo if the given reponame is not on the git server
function getwptheme() {
        if [ $* ]; then
                git clone git@cvs2:WP-Themes/$*.git $*;cd $*;git checkout develop
                if [ -f "gulpfile.js" ]; then
                        nvm use 6.11.1
                elif [ -f "Gruntfile.js" ]; then
                        nvm use 0.10.25
                        npm install node-sass request@2.81.0
                else
                        printf "\nNo grunt or gulp file. Something must be TERRIBLY wrong! D:"
                        printf "\n(git clone probably failed. Check reponame?)\n"
                        return 0
                fi
                npm install
                bower update
                ## You will want to have [gitflow "prefix"]   in your ~/.gitconfig file
                                          versiontag = v
                git flow init -d
        else
                printf "\nNo repoName found."
                printf "\nUsage: getwptheme repoName\n"
                return 0
        fi
}