Setting Up Custom Post Types + MetaBoxes for Understraps

To set up Custom Post Types & Metaboxes for the Understrap Child template you need to do four things.

  1. Copy your cmb2 folder into vendors
  2. Add custom-metaboxes.php to inc folder in child directory
  3. Add custom-post-type.php to inc folder in child directory
  4. require new scripts in functions.php

1. Create the CMB2 folder

Go to the GitHub project for CMB2 and download the project.

Copy the following folders and files to the vendor folder in your child theme (you will need to create this if it doesn’t exist).

/css

/images

/includes

/js

/languages

bootstrap.php

index.php

init.php

2. Create custom-metaboxes.php

Copy the contents of example-functions.php and copy them into a new file: inc/custom-metaboxes.php

Edit lines 16 – 19 to redefine the path to include the vendors folder

if ( file_exists( dirname( __FILE__ ) . '/../vendors/cmb2/init.php' ) ) {
require_once dirname( __FILE__ ) . '/../vendors/cmb2/init.php';
} elseif ( file_exists( dirname( __FILE__ ) . '/../vendors/CMB2/init.php' ) ) {
require_once dirname( __FILE__ ) . '/../vendors/CMB2/init.php';

Copy and replace all instances of your_prefix with the project prefix.

3. Create the custom-post-type.php

The file needs to have the following functions and actions: A function and action to flush rewrite rules for custom post types, A function and action to register CPTs (using register_post_type() function), A function and action to define the metaboxes for each custom post type.

Use the example below as a starting point (don’t forget to find and replaceyour_prefix with the project prefix) :

<?php
/* Custom Post Type Example – stolen from bonestheme
This page walks you through creating
a custom post type and taxonomies. You
can edit this one or copy the following code
to create another one.

Developed by: Eddie Machado
URL: http://themble.com/bones/

Remember to replace ‘your_prefix_’ with theme name.

*/

// Flush rewrite rules for custom post types
add_action( ‘after_switch_theme’, ‘your_prefix_flush_rewrite_rules’ );

// Flush your rewrite rules
function your_prefix_flush_rewrite_rules() {
flush_rewrite_rules();
}

/*
Register my Custom Post Types
*/

function cpt_register() {
// SERVICES CUSTOM POST TYPE
// creating (registering) the custom type
register_post_type( ‘services’, /* (http://codex.wordpress.org/Function_Reference/register_post_type) */
array( ‘labels’ => array(
‘name’ => __( ‘Services’, ‘bc’ ), /* This is the Title of the Group */
‘singular_name’ => __( ‘Service’, ‘bc’ ), /* This is the individual type */
‘all_items’ => __( ‘All Services’, ‘bc’ ), /* the all items menu item */
‘add_new’ => __( ‘Add New’, ‘bc’ ), /* The add new menu item */
‘add_new_item’ => __( ‘Add New Service’, ‘bc’ ), /* Add New Display Title */
‘edit’ => __( ‘Edit’, ‘bc’ ), /* Edit Dialog */
‘edit_item’ => __( ‘Edit Service’, ‘bc’ ), /* Edit Display Title */
‘new_item’ => __( ‘New Service’, ‘bc’ ), /* New Display Title */
‘view_item’ => __( ‘View Service’, ‘bc’ ), /* View Display Title */
‘search_items’ => __( ‘Search Service’, ‘bc’ ), /* Search Custom Type Title */
‘not_found’ => __( ‘Nothing found in the Database.’, ‘bc’ ), /* This displays if there are no entries yet */
‘not_found_in_trash’ => __( ‘Nothing found in Trash’, ‘bc’ ), /* This displays if there is nothing in the trash */
‘parent_item_colon’ => ”
), /* end of arrays */
‘description’ => __( ‘Financial Services Offered’, ‘bc’ ), /* Custom Type Description */
‘public’ => true,
‘publicly_queryable’ => true,
‘exclude_from_search’ => false,
‘show_ui’ => true,
‘query_var’ => true,
‘menu_position’ => 15, /* this is what order you want it to appear in on the left hand side menu */
‘menu_icon’ => ‘dashicons-format-aside’, /* the icon for the custom post type menu */
‘rewrite’ => array( ‘slug’ => ‘services’, ‘with_front’ => false ), /* you can specify its url slug */
‘has_archive’ => ‘financial-services’, /* you can rename the slug here */
‘capability_type’ => ‘post’,
‘hierarchical’ => false,
/* the next one is important, it tells what’s enabled in the post editor */
‘supports’ => array( ‘title’, ‘editor’, ‘page-attributes’, ‘thumbnail’, ‘excerpt’, ‘author’,’revisions’)
) /* end of options */
); /* end of register post type */
}

// adding the function to the WordPress init
add_action( ‘init’, ‘cpt_register’);

/***********************************************
* Meta Boxes for SERVICES CPT
************************************************/

add_action( ‘cmb2_admin_init’, ‘your_prefix_register_services_metabox’ );
// Hook in and add a metabox. Can only happen on the ‘cmb2_admin_init’ or ‘cmb2_init’ hook.
// cmb2_admin_init is defined in bootstrap.php

function your_prefix_register_services_metabox() {
$prefix = ‘your_prefix_services_’;

$cmb_services = new_cmb2_box( array(
‘id’ => $prefix . ‘metabox’,
‘title’ => esc_html__( ‘Service Options’, ‘cmb2’ ),
‘object_types’ => array( ‘services’, ), // Post type
) );

$cmb_services->add_field( array(
‘name’ => esc_html__( ‘Icon’, ‘cmb2’ ),
‘desc’ => esc_html__( ‘Icon to be displayed on Services menu’, ‘cmb2’ ),
‘id’ => $prefix . ‘icon’,
‘type’ => ‘file’
) );

}

?>

 

4. Add require commands in functions.php

Open the child theme’s functions.php file and paste the following:

// Add Custom Meta Box
/**
* Load Custom Metabox infomation
*/
require get_stylesheet_directory() . ‘/inc/custom-metaboxes.php’;

/**
* Load Custom Post Type
*/
require get_stylesheet_directory() . ‘/inc/custom-post-type.php’;

WordPress + Understrap (with SASS + GIT) set up (locally)

Worpress installation.

Download the latest version of WordPress from wordpress.org. Unzip the folder and move the new folder to your sites directory. Rename the wordpress folder to your project name.

Database

Launch phpMyAdmin. Create a new database, user and password. Make a note of these details.

Understrap Theme

Log into WP-Admin. Go to Appearance -> Themes.  Press the Add New button and search for Understrap. Install and activate.

Create Child Theme & set up Visual Studio Code Workspace

Go to the Understrap Child GitHub Project page. Download the project folder. Unzip and move to the wp-content/themes folder.

Rename as per your project.

Open up Visual Studio Code. Select Add Folder to Workspace. Select the new renamed child theme folder and drag into the Explorer window.

Save as new workspace (save this into the main work folder, not the _site folder.

Create new Screenshot.png

Open up a new file in Illustrator or Photoshop – artboard size 880px x 660px. Create new screenshot image and save as wp-content/themes/childtheme/screenshot.png

Edit style.css with theme information

Open up style.css and edit with relevant theme information.

Go into Appearance->Themes and activate the new child theme.

Setting up Sass, JS compilation and BrowserSync

The gulp task ‘watch-bs’ (as defined in gulpfile.js) Starts the Sass watcher (watch), Javascript watcher (scripts) and the browser-sync function.

Custom Javascript

The gulpfile.js identifies the path src/js/custom-javascript.js for custom scripts so create this file and add any custom JS to this file.

Sass

The Gulp watch task monitors any .scss file within any folder within the sass folder (ie assets or themes).

Make any variable changes within _child_theme_variables.scss

Create your own files within the theme directory to simplify things for example:

_header.scss

_navigation.scss

_footer.scss

_utilities.scss

_base.scss

_components.scss

_mixins.scss

You could create an individual folder for each of the pages ie:

sass/pages/_home.scss

sass/pages/_contact.scss

Make sure to @import any custom partials in child-theme.scss

Browser Sync

To utilise browserSync you must configure the proxy option in browserSyncOptions in gulpconfig.json

eg: “proxy” : “localhost:800/randrgardenlandscapes.co,.uk

Compiling using Gulp

First install dependencies (node.js and browsersync must be installed globally)

Open terminal and cd to the theme root folder OR open Terminal->New Terminal in VisualStudio Code and type the following command

npm install

Start Gulp watch, scripts and Browsersync with the following command:

gulp watch-bs

*To stop gulp watch service, press ctrl+C

Setting Up Git

STEP 1: Create local GIT repository
  • Open Terminal
  • CD to root of intended repository
  • type: git init
  • Create a .gitignore file if you don’t want files to be included
STEP 1.2 : Initial Commit
git add -A to add all untracked and modified files
git commit -a -m “initial commit”
Set up remote Repository: BITBUCKET / GIT
STEP 2: Create remote Bitbucket repo
  • Log in to Bitbucket (duncan@samwell.me) / GIT veryselfishman
  • Create a new Repository
STEP 3: Clone and migrate local repo
  • Open terminal and CD to the path of the local repository
  • Type the following code:
git push -u origin master
You can use GitLens in Visual Studio to track, commit and push Git changes.

PHP MySQL login system

Taken from TutorialRepublic.

User Authentication Mechanism

The Registration System

This section will demonstrate how to build a registration system that allows users to create a new account.

Step 1: Creating the Database Table

First build a users table by executing the following SQL code:

CREATE TABLE users (
 id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
 username VARCHAR(50) NOT NULL UNIQUE,
 password VARCHAR(255) NOT NULL,
 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

Step 2: Creating the Config File

Create this Object Orientated PHP include file that will be called when a connection to the MySQL database is required.

<?php /* Database credentials. Assuming you are running MySQL server with default setting (user 'root' with no password) */

define('DB_SERVER', 'localhost'); 

define('DB_USERNAME', 'root'); 

define('DB_PASSWORD', '');

 define('DB_NAME', 'demo'); 

/* Attempt to connect to MySQL database */

$mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
 
// Check connection
if($mysqli === false){
die("ERROR: Could not connect. " . $mysqli->connect_error);
}
?>

Step 3: Creating the Registration Form

Create a new include file in the root called register.php to create new users and their password hash

<?php
// Include config file
require_once "config.php";
 
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
    // Validate username
    if(empty(trim($_POST["username"]))){
        $username_err = "Please enter a username.";
    } else{
        // Prepare a select statement
        $sql = "SELECT id FROM users WHERE username = ?";
        
        if($stmt = $mysqli->prepare($sql)){
            // Bind variables to the prepared statement as parameters
            $stmt->bind_param("s", $param_username);
            
            // Set parameters
            $param_username = trim($_POST["username"]);
            
            // Attempt to execute the prepared statement
            if($stmt->execute()){
                // store result
                $stmt->store_result();
                
                if($stmt->num_rows == 1){
                    $username_err = "This username is already taken.";
                } else{
                    $username = trim($_POST["username"]);
                }
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
        }
         
        // Close statement
        $stmt->close();
    }
    
    // Validate password
    if(empty(trim($_POST["password"]))){
        $password_err = "Please enter a password.";     
    } elseif(strlen(trim($_POST["password"])) < 6){
        $password_err = "Password must have atleast 6 characters.";
    } else{
        $password = trim($_POST["password"]);
    }
    
    // Validate confirm password
    if(empty(trim($_POST["confirm_password"]))){
        $confirm_password_err = "Please confirm password.";     
    } else{
        $confirm_password = trim($_POST["confirm_password"]);
        if(empty($password_err) && ($password != $confirm_password)){
            $confirm_password_err = "Password did not match.";
        }
    }
    
    // Check input errors before inserting in database
    if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
        
        // Prepare an insert statement
        $sql = "INSERT INTO users (username, password) VALUES (?, ?)";
         
        if($stmt = $mysqli->prepare($sql)){
            // Bind variables to the prepared statement as parameters
            $stmt->bind_param("ss", $param_username, $param_password);
            
            // Set parameters
            $param_username = $username;
            $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
            
            // Attempt to execute the prepared statement
            if($stmt->execute()){
                // Redirect to login page
                header("location: login.php");
            } else{
                echo "Something went wrong. Please try again later.";
            }
        }
         
        // Close statement
        $stmt->close();
    }
    
    // Close connection
    $mysqli->close();
}
?>
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sign Up</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
    <style type="text/css">
        body{ font: 14px sans-serif; }
        .wrapper{ width: 350px; padding: 20px; }
    </style>
</head>
<body>
    <div class="wrapper">
        <h2>Sign Up</h2>
        <p>Please fill this form to create an account.</p>
        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
            <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
                <label>Username</label>
                <input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
                <span class="help-block"><?php echo $username_err; ?></span>
            </div>    
            <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
                <label>Password</label>
                <input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
                <span class="help-block"><?php echo $password_err; ?></span>
            </div>
            <div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
                <label>Confirm Password</label>
                <input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
                <span class="help-block"><?php echo $confirm_password_err; ?></span>
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-primary" value="Submit">
                <input type="reset" class="btn btn-default" value="Reset">
            </div>
            <p>Already have an account? <a href="login.php">Login here</a>.</p>
        </form>
    </div>    
</body>
</html>

Setting up Sass

Install Sass in local environment

Create a folder called sass and a file within that called main.scss

(You can use terminal commands (mkdir, touch))

Configuring package.json

Determine how to compile sass by setting scripts in package.json

"scripts": {
 "compile:sass": "node-sass sass/main.scss css/style.css -w"
},

To compile Sass, open terminal and type:  npm run compile:sass

The -w tag will watch for changes within the source file and auto compile.

Live Server

Install using npm

npm install live-server -save

or install globally

sudo npm install live-server -g

type live-server in command prompt and cmd will auto launch

Installing Sass locally using NPM

NPM & the Node Ecosytem

node.js

An open source JavaScript runtime, allows developers write and run JS app on the server. Can also be used to write tools to help with local web development.

NPM

Node Package Manager. Command line interface to allow installation and management of packages on local systems.

Make sure the latest version of node.js is installed (download from node.js website).

node -v on the command line will inform you what version of node.js is on the system.

package.json

First thing to create when creating a new project. Will contain the definitions of the project and where NPM will install the tools and packages its required.

npm init will help you create a package.json file.

You can use pakage.json file to install all the dependencies if you need to work on the project elsewhere, just type npm install

Install Sass

$ npm install node-sass --save-dev

Use NPM to install other dependencies such as jquery (include –save)

npm install jquery --save

This will show in the dependencies (not the devdependencies.

When setting up GIT, make sure to ignore all node_modules so as not to include all the dependencies

Sass – the basics

Features

  • Variables: for reusable values such as colours, font-sizes, spacing, etc;
  • Nesting: To nest selectors inside of one another, allowing us to write less code;
  • Operators: For mathematical operations right inside of CSS;
  • Partials & Imports: To write CSS in different files and importing them all into one single file;
  • Mixins: To write reusable pieces of CSS code;
  • Functions: similar to mixins, with the difference that they produce a value that can then be used; ie darken(color, i%)
  • Extends: To make different selectors inherit declarations that are common to all of them;
  • Control Directives: for writing complex code using conditionals and loops;

Sass syntax vs SCSS syntax

Sass: no requirement for brackets or semi-colons

SCSS similar to traditional CSS, clearer to follow and easier to convert old CSS projects.

Mixins, Functions & Extends

Mixins

ie Clearfix mixin:

@mixin clearfix {
 &::after {
  content: "";
  clear: both;
  display: table;
 }
}

nav {
 @include clearfix;
}

Mixins are groups of CSS that can be reused. Use @include to insert the mixin.

You can also pass arguments through mixins:

@mixin style-link-text($colour) {
 text-decoration: none;
 text-transform: uppercase;
 color: $colour;
}

@include style-link-text(#FFF);

Functions

Functions are like mixins but you can perform mathematical action using arguments passed in parenthesis:

@function divide($a, $b) {
 return $a / $b;
}

Sass has a number of built in functions such as darken() and lighten().

Extends

 

%btn-placeholder {
 styling
}

extend %btn-placeholder

Like mixins, this allows you to reuse code, however instead of copying the code to each element, when compiled it will group all the elements together and apply the style. Use instead of mixins when the elements are related to each other.

WordPress Migration

  1. Install and activate All-in-One WP Migration plug in on local / test environment
  2. Go to destination site and install and activate the plug in.
  3. Go back to source site and Click on All-in-One WP Migration -> Export, save and download as file.
  4. Go to destination site.Click on All-in-One WP Migration -> Import. Select File and select downloaded source file.
  5. Save Permalinks on destination site.

Moving a WordPress site from a subdomain to the root

  1. Back up both sites to a file using All-in-One WP Migration
  2. Import dev site to live site using the same plug in
  3. Save Permalinks on destination site.

CSS Animations

Two Types of animation

@Keyfrees

Create a keyframes function:

 
@keyframes animationLabel {
0% {
opacity: 0;
transform: translateX(-100px); // this element will be reposition 100px to the left
}
100% {
opacity: 1;
transform: translate(0);
}
 
Use the following CSS tags to call the animation
.movingElement {
animation-name: moveInLeft;
animation-delay: 3s
animation-duration: 1s
animation-iteration-count: 3;
animation-timing-function: ease | ease-in | ease-out | ...
backface-visibility: hidden;
animation-fill-mode: backwards; //will automatically apply keyframe 0 before animation starts
}

Refer to online documentation for all the animation properties.

If animation is shakey use backface-visibility property on element.

Transition Property

button:hover {
 transform: translateY(-3px);
 box-shadow: 0 10px 20px rgba(0,0,0,.2);
}

button:active {
 transform: translateY(-1px);
 box-shadow: 0 5px 10px rgba(0,0,0,.2);
}

button:link, button:visited {
 transition: all .2s;
}

transition:  property | duration;