Brian Abbott IT Student Fri, 23 Nov 2018 18:32:31 +0000 en-US hourly 1 Functions Type Hinting and Void Functions in PHP 7 Fri, 23 Nov 2018 18:31:18 +0000 Overview

Since PHP5 functions had the ability to accept arrays and classes as parameter types. Now PHP 7 expands that list to bool, float, int, string. You can also set types for the return values, and allow for these values to accept a null value. Finally you can set a function as void which will prevent it from returning a value.

Return Values

Some functions return values, while some do not. For example, print returns a 1 or 0 indicating its success while echo does not. Functions that do not return a value (above examples) are called void functions.

function add_two_numbers($a, $b) {
  return $a + $b;

$sum = add_two_numbers(2, 2); // Stores 4 to $sum variable
$sum2 = add_two_numbers(3, 4); // Stores 7 to $sum variable


In the above example the function returns a value to a variable. Functions terminate when they reach the return statement. While it is possible to have multiple return statements inside of a function (conditionals or switch statement) only one of them can be used.

Void Functions

A void function does not return a value. The following function is a void function.

  function sayHello() {
    echo 'Hello, World!';

Returning Multiple Values With an Array


function generateRandomFirstName() {
  // code to generate name
  return $firstName;

function generateRandomLastName() {
  // code to generate name
  return $lastName;

function generateFullName() {
  $name = array();
  array_push($name, generateRandomFirstName(), generateRandomLastName());
  return $name;

list($firstName, $lastName) = generateFullName();

echo "Hello, $firstName $lastName.";

You can only return one value, but if you need to return multiple values, use an array. The example above demonstrates using the list function to return multiple values. Keep in mind if you need to use an array, just return that and don’t use list().

Making Function Arguments Optional

You can make function arguments optional to the client programmer by setting a default value in the parenthesis.

function bakeACake($glutenAllergy = false) {
    if (!$glutenAllergy) {
      echo 'Cake is done. Come eat it.';
    } else {
      echo 'You cannot have a cake because you are allergic to Gluten.';

  bakeACake(); // Outputs 'Cake is done. Come eat it.
  bakeACake(true); //Outputs You cannot have a cake because you are allergic to Gluten.

These ‘optional’ parameters must come after all required parameters.

Setting a Type for Parameters

PHP has the ability to declare types for the following values: class, array, bool, float, int, and string. This is pretty straightforward – the type precedes the variable.

function test(bool $testing) { } 

You can also provide that the argument can accept a null value. To do this put a ? in front of the type.

function test(?bool $testing) { } 


Also it should be noted that PHP will by default try to automatically type cast a variable. Consider the following code:

function greet(string $name) {
  echo "Hello, $name!";

greet(12); // Outputs Hello, 12!

To stop PHP from doing this add the following code to the top of your script


Declaring Return Type

Return types can be declared in PHP as seen below:

function greet(string $name): string {
  return "Hello, $name!";

Additionally you can allow the function to return null also by adding a question mark in front of the return type

function greet(string $name): ?string {
  return null;

Void Return Type


function void_one: void {
  return 1; // Fatal error: a void function must not return a value

function void_two: void {
  // valid

function void_three: void {
  return; // valid

function void_four: void {
  return null; // Fatal error: a void function must not return a value

As seen above PHP 7.1 supports a void return type.


]]> 0
PHP POST Form Inputs – Multidimensional Arrays Fri, 23 Nov 2018 18:10:00 +0000 In PHP it is common to have form inputs with the same name. Many times these will be generated dynamically (i.e. a WordPress Repeatable Custom Meta Field). PHP stores these values to the POST Superglobal as a multidimensional array. To begin with, run this example script here PHP Form Inputs Example.

Let’s say you have a text input for streets. You simply add brackets at the end of the name:

<input type="text" name="street[]">

When you submit the form as a POST value, you will be able to view the values as a multidimensional array starting at 0 (i.e. $_POST[‘street’][0], $_POST[‘street’][1], etc.).

To view the code of the example on GitHub click here.

]]> 0
Securing an Apache Virtual Site with a Self Signed Certificate Tue, 23 Oct 2018 16:36:59 +0000 This article follows the dev virtual site which can be viewed here. In that tutorial we created a virtual site called new site. The site we created was http meaning the packets are sent unencrypted. This means passwords and other data sent will be viewable to others on the network. A password to log into a content management system can easily be sniffed out. We can prevent this from happening by using a self signed TLS certificate, which will encrypt our traffic.

Let’s start by making a directory to store the certs

mkdir /etc/apache2/ssl

Next we will enter that directory and create a cert and private key inside of it.

cd /etc/apache2/ssl
sudo openssl req -x509 -newkey rsa:4096 -keyout newsite.local.key -out newsite.local.crt -days 365 -nodes

Next we will copy the default SSL config file

cd /etc/apache2/sites-available
sudo cp default-ssl.conf newsite-ssl.conf

We will now edit the config file so we have the following

                ServerAdmin webmaster@localhost
                ServerName newsite.local

                DocumentRoot /var/www/html/newsite/public_html

                ErrorLog /var/www/html/newsite/logs/error.loca
                CustomLog /var/www/html/newsite/logs/access.log combined

                SSLEngine on

                SSLCertificateFile      /etc/apache2/ssl/newsite.local.crt
                SSLCertificateKeyFile /etc/apache2/ssl/newsite.local.key

                                SSLOptions +StdEnvVars
                                SSLOptions +StdEnvVars

We will now enable the site.

sudo a2ensite newsite-ssl.conf
sudo service apache2 reload

The final step is to add a redirect to the newsite.conf file. Add the following line inside of the <VirtualHost *:80> tag

Redirect / https://newsite.local

If you did everything correctly you should get a warning that the connection is not secure. This is simply because the cert is not signed by a central authority. Your packets will be sent encrypted. Obviously this should not be done on a production server. For a production server check out Let’s Encrypt.

]]> 0
The CSS Cascade Tue, 16 Oct 2018 17:11:57 +0000 Inheritance makes it possible for a link to inherit CSS properties from both the <body> and <p> tags that precede it. It is possible for styles to collide, and there is a system, known as the css cascade that governs conflicting styles.

How Styles Cascade

The css cascade is a set of rules that determine which style properties get applied to an element. These happen in two ways:

  1. The same property is inherited from multiple ancestors
  2. One or more styles apply to the same element (i.e. a <p> with a <p> style and a class)

Inherited Styles Accumulate

A HTML element acquires formatting that its ancestors contained. Consider the following example

body { font-family: Veranda, Arial, Helvetica, sans-serif; }
p { color: #f30; }
strong { font-size: 24px; }

The strong tag contains the following styles

strong {
  color: #f30;
  font-size: 24px;

Nearest Ancestor Wins

In the above example, there were no conflicting styles. Imagine if there were. If there were the web browser would apply the style closest to the tag in question.

The Directly Applied Style Wins

Properties applied to a style directly beat out any conflicting inherited properties.

One Tag, Many Styles

Inheritance makes it possible for a tag to be affected by multiple styles. You can also have a tag have multiple styles apply from applying multiple styles to it. Imagine a <p> tag that has an internal sheet with a <p> style and an external sheet with a <p> style. Imagine that the <p> tag also has a class style applied to it.

This is fine if none of the styles are conflicting. The next section deals with how the css cascade handles conflicts.

Specificity: Which Style Wins

The CSS cascade follows a formula to determining specificity when multiple styles apply

    • A tag selector is worth 1 point
    • A class selector is worth 10 points
    • An ID selector is worth 100 points
    • An inline style is worth 1,000 points

Consider the following example:

a { font-weight: italic; }
p a { font-weight: bold; }
.byline a { font-weight: normal; }

The first style would have a specificity of 1 point. The second one of 2 points and the 3rd one of 11 points. The third one would be the winning style.

The Tiebreaker: Last Style Wins

p .email { color: blue; }
.byline a { color: red; }

In the above example (both styles targeting an <a> tag) the styles both have the same specificity. When this happens the browser applies the last stylesheet.

Overruling Specificity

If you add !important after any CSS property, it will apply and override more specific styles.

a {color: teal !important; }


Controlling the Cascade

If there is a style with a greater specificity you have two options. First you can add important!. Second you can add more specificity to the style. It is best to change the specificity and only use important for real emergencies.

CSS Cascade Conclusion

This concludes the tutorial on the CSS Cascade. Hopefully next time you are writing CSS and wondering why the style you wrote won’t apply you will be able to troubleshoot better.

]]> 0
CSS Inheritance Mon, 15 Oct 2018 19:27:28 +0000 Children inherit many traits from parents such as eye color, hair color, male pattern baldness etc. HTML tags can inherit CSS properties from their ancestors as well.

What is Inheritance?

Inheritance is the process in which CSS properties applied to a tag are passed on to nested tags. A <p> tag will be inside of the <body> tag – styles applied to the body tag will be applied to the <p> tag.

Inheritance works through multiple generations. If an <em> and <strong> tag appear inside of a <p> tag they inherit properties applied to the <body> tag. While this may seem confusing, it ensures that you don’t have to repeatedly apply styles.

In addition to tag styles inheriance works with class styles, ID styles, descendant selectors, etc.

How Inheritance Streamlines Style Sheets

If you want to pass styles onto ancestor tags, create a type selector tag for the body (or create a class and apply it to the body). The styles will be applied.

The Limits of Inheritance

Many CSS Properties don’t pass down to descendant tags. An example is the border tag. If a border was applied to every descendant tag it would mess things up.

]]> 0
CSS Selectors Mon, 15 Oct 2018 19:04:30 +0000 CSS Selectors

CSS Selectors give you the ability to select specific HTML entities to apply styling. This post will give an overview of CSS Selectors.

Type Selectors

Selectors used to style HTML tags are called type or element selectors. These will apply styles to every tag of that type on the page.


h2 {
  font-family: "Century Gothic", "Gill Sans", sans-serif;
  color: #000000;
  margin-bottom: 0;

Class Selectors

Class selectors select a HTML class. Classes, unlike IDs apply to multiple elements. The elements can be of the same of different type.

  • All class selector names must begin with a period
  • CSS permits only letters, numbers, hyphens, and underscores in class names
  • After the period, the name must start with a letter
  • Class names are case-sensitive
.special {
  color: #FF0000;
  font-family: "Monotype Corsiva"

ID Selectors

HTML ID Selectors can only be used for one element on a page. ID selectors are not used with CSS as often as they used to be. Using multiple IDs in descendant selectors can make it difficult to determine specificity and easy to accidentally overwrite other styles.

  #banner {
    background: #cc0000;
    height: 300px;
    width: 720px;

Styling Groups of Tags

A group selector selects a group of elements to apply style to.

Constructing Group Selectors

Simply list the selectors you want to target, separated by commas.  The selectors can be of any type in CSS.

h1, h2, h3, h4, h5, h6 {
  color: #F1CD33;

h1, p, .copyright, #banner {
  color: #F1CD33;

The Universal Selector (Asterisk)

An asterisk (*) selects every single tab on the page.

* {
  font-weight: bold;

Styling Tags Within Tags

Descendant selectors allow you to select elements that are descendants of other elements. For example say you want to target a <strong> tag when it is inside of a <h1> tag. The selector below selects a <strong > tag that is a descendant of a <h1> tag.

h1 strong {
  color: red;

Descendant selectors can contain more than one tag:

ul li a
body li a
html li a
html body ul li a

It is considered better practice to use shorter descendant selectors.

When creating descendant selectors you aren’t just limited to type selectors. You can build complex descendant selectors combining different types of selectors.

.intro a { color: yellow; }

Creating Modules

Descendant Selectors are often used to format a module of code. That is a collection of HTML that serves a particular function on a page.

The following descendant selectors can be used to style a module (a div with the class of news and a h2 and p element inside).

.news h2 { color: red; }
.news p { color: blue; }

It’s also common to create descendant selectors with multiple class names, giving a class name to the descendant elements.

.contact .name { font-weight: bold; }
.contact .phone { color: blue; }
.contact .address { color: red; }



The selector above may look like a descendant selector, but it is actually targeting a paragraph element with the class of intro.

Pseudo-Classes and Pseudo-Elements

Pseudo Classes and Pseudo Elements allow you to select parts of a web page that don’t have tags, but are easy to identify.

Styles for Links

There are four pseudo-classes that let you format links in different states

  • a:link – selects and link that your guest hasn’t visited yet, while the mouse isn’t hovering over it or clicking it
  • a:visited – a link your visitor has clicked before
  • a:hover – lets you change the look of a link as your visitor passes the mouse over it
  • a:active – lets you determine how a link looks as your visitor clicks it

Styling Paragraph Parts

The :first-letter pseudo element targets the first letter of the targeted element.

The :first-line pseudo element targets the first line of the targeted element.

More Pseudo-Classes and Pseudo-Elements


:focus applies when the visitor does something to indicate their attention to a web page element – usually by clicking or tabbing into it. The :focus selector can be used to change the background color of a text box after the user clicks in when they are about to type.


The :before pseudo-element lets you add content preceding an element.

.tip:before {content: "Hot tip!" }


Like the :before selector but after the element.


Applies to highlighted text on a browser page.

::selection {
  color: #FFFFFF;
  background-color: #993366;

For more information on this pseudo class click here. To see an example of this pseudo class click here. Right click and select view source to view the source.

Attribute Selectors

Attribute selectors allow you to style a tag based on HTML attributes it has.


The above selector targets all img tags with a title attribute. These selectors can be used with classes too.


The above selector selects ever HTML element with class photo and a title attribute.

In addition to selecting elements that have a particular element you can select elements who have an exact value set for that attribute.

a[href=""] {
  color: green;
  font-weight: bold;

The above selector selects every link that points to Selecting the value of an attribute is useful when working with forms. The input element has many different attributes such as text, checkbox or radio.


The attribute selector also lets you select elements with an attribute value that begins withends with, or contains a certain value.


The ^= translates to begins with.

a[href$=".pdf"] {
  background: url(doc_icon.png) no-repeat;
  padding-left: 15px;

The $= translates to ends with.


The *= translates to contains so the above selector selects all images whose src attribute contains the word headshot.

Child Selectors

To target the child of another tag, use the child selector.

body > h1

The above selector selects any <h1> tag that is a child of the <body> tag.

Pseudo Classes

CSS includes pseudo-classes for selecting child elements. To make these easier to understand I created a page that demonstrates their usage. It can be viewed here.

Child Type Selectors

Child Type selectors are similar to child selector pseudo classes, except they apply to a particular type. Like child selectors they can be combined with descendant selectors. Unlike child selectors they target a child of a particular type. To see an example of these selectors click here.


A tag that appears immediately after another tag in HTML is called an adjacent sibling. Adjacent sibling selectors can be used to give the first paragraph after each heading a different formatting for paragraphs that follow.

h2 + p

The above selector selects every paragraph that follows each <h2> tag.

The :target Selector

The :target selector allows you to target an element with an id, when that ID is the target of a link.

Consider a link that links to a section of the page with an ID of #contact. When that link is selected the ID appears in the browser and it scrolls down to that section of the page. The id #contact appears in the URL after the file path. The target selector allows you to target the element when it has been targeted by a link (and appears in the URL).

To view an example click here.

The :not() Selector

The :not() selector (aka negation pseudo-class) lets you select something that’s not something else.

p:not(.classy) { color: blue; }

This CSS Selector selects every <p> that does not have the class ‘classy’.

The not selector can also come in handy with attribute selectors. Consider the following CSS Selector


This selector selects all absolute URLs (ones beginning with http). If you use absolute URLs for links on your own page, the style would apply to those. To make it apply to all absolute links OUTSIDE of your page you could do this


CSS Selectors Conclusion

This concludes the tutorial on CSS Selectors. For more information please view Mozilla CSS Reference.

]]> 0
How to Set Up Apache Virtual Hosts for Development on Ubuntu Mon, 15 Oct 2018 12:59:56 +0000 There are a many tutorials that explain how to set up virtual hosts for a production server on Apache. It’s not that different for a development enviornment, but there aren’t very many tutorials on how to do this.

The main difference is instead of pointing the DNS of a domain to your server’s IP Address you need to map your /etc/hosts file from a local domain you selected to a local loopback address (the most common of these being

This tutorial assumes that you have a LAMP stack installed on your Linux Desktop. If you do not I will have a tutorial up on that soon. Alright, let’s begin.

The first thing you want to do is go to your sites-available folder.

cd /etc/apache2/sites-available

This folder will contain the config files for all of the virtual sites you have created. If you have not created any, you should have a file 000-default.conf. Let’s copy that folder and name it newsite.conf.

sudo cp 000-default.conf newsite.conf

Let’s take a look at that config file

sudo nano newsite.conf

We have the following text inside (comments removed):

<VirtualHost *:80>

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined


We’re going to edit this information, then I will explain it below.

<VirtualHost *:80>
        ServerName newsite.local

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html/newsite/public_html

        ErrorLog /var/www/html/newsite/logs/error.log


ServerName refers to the domain name you will select. For a production environment this will be the domain name you selected. For a development environment it will be a domain name you select. You can use almost any TLD, but I tend to use .local. Note that the TLD .dev will not work.

DocumentRoot refers to the directory that will contain the index page of the site. I usually place the document root in a public_html file inside of a site’s directory. That way I can place DB connection files inside of the site name folder. This is a security measure – say PHP is misconfigured and Apache is just loading PHP code. A hacker can load any file and see the code. Placing the DB connection file outside of the server ensures they won’t be able to get the connection information.

ErrorLog refers to the location of the Apache error log for this site. The CustomLog refers to the access log. Both of these are stored in a log file inside of the logs folder in the newsite directory.

Next we need to create the directory.

mkdir -p /var/www/html/newsite/logs
mkdir -p /var/www/html/newsite/public_html

Once the directory exists we can add newsite.local (the url we selected) to the /etc/hosts file. /etc/hosts maps domain names to IP addresses. We will map it to

sudo nano /etc/hosts    newsite.local

Save the file and close it.

Finally we want to enable the site with Apache.

sudo a2ensite newsite.conf
sudo service apache2 reload

If you haven’t had any typos in your configuration files you should have a new virtual site working.

]]> 0
WordPress Ajax Autocomplete with Custom Post Types and Meta Fields Sun, 14 Oct 2018 18:34:21 +0000 Setup

WordPress Ajax Autocomplete works essentially the same as it does when you are creating a site from scratch. You create a list of terms in JSON format and provide those as a source. There are two main differences with WordPress Ajax Autocomplete and building from scratch:

  1. For the source instead of linking a file you localize a script. What that means is WordPress creates an Object with the values listed and writes it directly in the HTML about the script that requires it. If you are confused, see the image above.
  2. For the Ajax call you don’t create a custom page. Instead you make a post request to the admin-ajax.php file which is located inside of the wp-admin directory.

The code for this tutorial can be downloaded from GitHub here.

Alright, let’s get to it!

In this tutorial we will create a custom post type called bands. Each band will have a custom meta field for the guitarist, singer, bass player and drummer. When a user visits our band page and starts typing musicians our application will pull from the custom meta fields of each post using WordPress Ajax Autocomplete. When a selection is made, the page will display the content of the custom post type which will be a Bootstrap 3 panel. This tutorial makes use of jQuery for Ajax. Because we are using the panels we will need a theme that supports Bootstrap3. Download the theme ‘Echo Magazine‘ and activate it.

Open your IDE of choice (I recommend PHPStorm) and navigate to the plugins directory (wp-content/plugins). Create a new directory called ‘bands’. Inside of that directory create a file called bands.php.

Creating the Custom Post Type

Let’s create the custom post type. In your bands.php file paste in the following code

* Plugin Name: Heady Bands
* Description: Creates a custom post type 'bands' with meta fields and an Ajax autocomplete field.
* Version: 1.0
* Author: Brian Abbott
* Author URI:

Go to the plugins page on your WP admin. You should see the plugin ‘Heady Bands’ listed as a plugin. Go ahead and activate it.

After that enter the following code on bands.php.

//////// Create Bands Custom Post
function heady_bands_custom_post() {
$labels = array(
'name'               => _x( 'Bands', 'post type general name' ),
'singular_name'      => _x( 'Band', 'post type singular name' ),
'add_new'            => _x( 'Add New Band', 'Group' ),
'add_new_item'       => __( 'Add New Band' ),
'edit_item'          => __( 'Edit Band' ),
'new_item'           => __( 'New Band' ),
'all_items'          => __( 'All Bands' ),
'view_item'          => __( 'View Band' ),
'search_items'       => __( 'Search Bands' ),
'not_found'          => __( 'No Bands found' ),
'not_found_in_trash' => __( 'No Bands found in the Trash' ),
'parent_item_colon'  => '',
'menu_name'          => 'Bands'
$args = array(
'labels'        => $labels,
'description'   => 'Menu area to add Bands',
'public'        => true,
'publicly_queryable' => true,
'menu_position' => 35,
'menu_icon'     => 'dashicons-format-audio',
'supports'      => array( 'title', 'thumbnail', 'page-attributes', 'editor' ),
'has_archive'   => false,
'show_in_rest' => false

register_post_type( 'bands', $args );
add_action( 'init', 'heady_bands_custom_post' );

This should create a custom post type called ‘Bands’. You will need to flush your permalinks to use this post type. Go to settings > permalinks and click save.

WordPress custom post type
We have now created a custom post type called bands.

Populating Data

Let’s fill out the information. I’ve written some HTML in a text document. Follow the instructions and make sure to paste the HTML into the ‘text’ section of your editor. When you are done push publish.

WordPress editor without styles.
The editor is not displaying the Bootstrap CSS while you edit. We’re going to fix this.

The editor is not showing the Bootstrap panel styles, we want to display the styles in the editor. To begin with I’ve added the styles to a CSS file you can download here. Add this file to the ‘bands’ directory you created. Next, in your bands.php page enter the following:

//////// Adds Panel Styles to the Editor
function rates_editor_style($mce_css) {
	$mce_css .= ', ' . plugins_url( 'custom-editor-style.css', __FILE__ );
	return $mce_css;

add_action( 'mce_css', 'rates_editor_style' );
WP Custom post type with styles
The editor is now displaying the styles.

Next we need to add Custom Meta Fields.

Custom Meta Fields

Custom meta fields are versatile. You can take any form input and store data with that post. They can also be repeatable which is useful for some situations. We will be using text inputs. We will have an input for guitarist, singer, bassist and drummer and we will use these values in our Ajax Autocomplete text field. When one of these is selected we will display the content of the custom post (the Bootstrap panel) that corresponds with the custom meta field.

To add a meta box you use the ‘add_meta_boxes’ filter. Paste the following on your bands.php file

function heady_bands_musicians_meta_box() {
		'musicians', // id
		'Musicians', // title
		'heady_bands_fields', // callback
		'bands', // screen
		'normal', // $context
		'high' // $priority
add_action( 'add_meta_boxes', 'heady_bands_musicians_meta_box' );

Now we will create the callback function

function heady_bands_fields() {
   global $post;
   $meta_guitarist = get_post_meta( $post->ID, 'guitarist', true );
   $meta_bassist = get_post_meta( $post->ID, 'bassist', true );
   $meta_singer = get_post_meta( $post->ID, 'singer', true );
   $meta_drummer = get_post_meta( $post->ID, 'drummer', true ); ?>

   <input type="hidden" name="your_meta_box_nonce" value="<?php echo wp_create_nonce( basename(__FILE__) ); ?>">

        <label for="guitarist">Guitarist</label>
        <input type="text" name="guitarist" id="guitarist" class="guitarist" value="<?php echo $meta_guitarist; ?>">
        <label for="bassist">Bassist</label>
        <input type="bassist" name="bassist" id="bassist" class="regular-text" value="<?php echo $meta_bassist; ?>">
        <label for="singer">Singer</label>
        <input type="text" name="singer" id="singer" class="regular-text" value="<?php echo $meta_singer; ?>">
        <label for="drummer">Drummer</label>
        <input type="text" name="drummer" id="drummer" class="regular-text" value="<?php echo $meta_drummer; ?>">

<?php }

Next we will create a function to save the custom meta fields.

function save_your_fields_meta( $post_id ) {
   // verify nonce
   if ( !wp_verify_nonce( $_POST['your_meta_box_nonce'], basename(__FILE__) ) ) {
      return $post_id;
   // check autosave
      return $post_id;
   // check permissions
   if ( 'bands' === $_POST['post_type'] ) {
         return $post_id;
         return $post_id;

   $guitarist = $_POST['guitarist'];
   $singer = $_POST['singer'];
   $bassist = $_POST['bassist'];
   $drummer = $_POST['drummer'];

      update_post_meta( $post_id, 'guitarist', $guitarist );
      update_post_meta( $post_id, 'singer', $singer );
      update_post_meta( $post_id, 'bassist', $bassist );
      update_post_meta( $post_id, 'drummer', $drummer );

add_action( 'save_post', 'save_your_fields_meta' );

Add each of the members from the custom post text to the meta fields. Once you have filled out the fields you are ready for the final step.

custom meta fields
Custom Meta Fields that have been completed.

WordPress Ajax Autocomplete

We have created a custom post type and completed a few of these with some HTML. We added some custom meta fields and completed these. The custom meta fields will be used as the autocomplete suggestions. When a user searches on a form they will be given the meta fields as suggestions. When they select one, the page will use Ajax to load the content of the custom post type.

To accomplish this we need to do is enqueue scripts. We will be using our own versions of jQuery and jQuery-ui due to compatibility issues.

After that we have to localize the autocomplete suggestions. The reason we are doing this is because WordPress uses Apache mod rewrite. Instead of linking to a URL that generates the JSON we will paste it in the body of the HTML as a JavaScript variable. This will give our script access to the JSON.

Let’s start by creating the function that will generate the JSON that will be used by the autocomplete.

function bands_generate_selections() {
   $json_array = array();
   $args = array( 'post_type' => 'bands', 'posts_per_page' => 100 );
   $loop = new WP_Query( $args );
      $guitarist = get_post_meta($loop->post->ID, 'guitarist', true);
         $array = array('label' => $guitarist, 'value' => $loop->post->ID);
         $json_array[] = $array;
      $singer = get_post_meta($loop->post->ID, 'singer', true);
         $array = array('label' => $singer, 'value' => $loop->post->ID);
         $json_array[] = $array;
      $bassist = get_post_meta($loop->post->ID, 'bassist', true);
         $array = array('label' => $bassist, 'value' => $loop->post->ID);
         $json_array[] = $array;
      $drummer = get_post_meta($loop->post->ID, 'drummer', true);
         $array = array('label' => $drummer, 'value' => $loop->post->ID);
   $json_data = json_encode($json_array);
   return $json_data;

Next we will create a file called ‘bands.js’ inside of our bands directory.

After that we will create a file to enqueue our JavaScript and CSS files.

function bands_enqeue_scripts() {
   wp_register_style('jquery-ui-style', '');
   wp_deregister_script( 'jquery' );
   wp_register_script( 'jquery', '', null, '3.3.1', true);
   wp_register_script('jquery-ui', '', 'jquery', '1.12.1', true);
   wp_enqueue_script( 'bands', plugin_dir_url( __FILE__ ) . 'bands.js',array('jquery', 'jquery-ui'), '1.0', true );
   $bands_autocomplete = bands_generate_selections();
   wp_localize_script('bands', 'band_members', array('autocomplete' => $bands_autocomplete ) );
add_action('wp_enqueue_scripts', 'bands_enqeue_scripts');

If you’ve done everything correctly, you should be able to load a web page, view the source, and see the JSON in the source.

The JSON inside of the HTML docucment.
The JSON inside of the HTML docucment.

The next thing we will do is create a function that will configure WP for our Ajax call. WordPress has a dedicated file for Ajax and we need to configure it with a hook.

function bands_ajax_listing() {
   $args = array(
      'p'         => $_POST['id'], // ID of a page, post, or custom type
      'post_type' => 'any'
   $loop = new WP_Query( $args );
      $post = the_content();

   echo $post;

   die(); //stop "0" from being output

add_action('wp_ajax_get_listing_names', 'bands_ajax_listing');

Now we are almost done, we just need to create the jQuery for the bands.js file, and add some HTML.

Let’s start by adding some HTML. Create a new page called bands. Inside of your text editor add this (as text not visual)

<input id="bands-input" class="float-left" name="bands-input" size="29" type="text" placeholder="Search by band members" >
<div class="bands"
<div id="bands" class="text-center">Please make a selection.</div>

Finally add this to your bands.js file

$(function() {
    let band_id;
    let autocomplete_terms = JSON.parse( band_members.autocomplete );
        source: autocomplete_terms,
        minLength: 1,
        select: function( event, ui ) {
            band_id = ui.item.value;
            if (event.type === 'click')
                band_id = ui.item.value;
                type: "POST",
                data: 'action=get_listing_names&id='+band_id,
                success: function(data) {


That’s it. You should now have a working WordPress Ajax Autocomplete.

The suggestions are added by jQuery autocomplete
The suggestions are added by jQuery autocomplete
WordPress uses Ajax to dynamically render the post content into the page.
]]> 0
Diatonic Chordal Modal Theory – The Modes Tue, 01 May 2018 17:39:27 +0000 When I was learning guitar this thing called the modes kept popping up. It became something I tried to understand repeatedly. I asked a couple of different teachers and nothing clicked until I met John Banks. John taught me when I had decided to go to school for music. Last minute was an understatement…I decided that’s what I would do and I put my mind to it.

While I studied under John he explained a fundamental concept of music theory – how to stack thirds to build chords (and recognize the modes inside of them). Chords and modes are related – to fully understand them you need to intellectualize the intervals of the mode and the extensions of the chord.

Another resource that helped me is High Country Guitar. High Country guitar allowed me to jam along with tracks. This put the sound of the mode in my head and helped me intuitively learn how to play it by ear. The website design has changed, but I plan to draw from it, and from what John taught me to teach the modes to guitarists.

The site will be called Diatonic Chordal/Modal Theory. It will consist of multiple websites that each teach a section of the course. The course will have a main site, with forums. When you click on a user’s name you will be able to see the utilities (quizzes) that they have completed. Each utility will have a leader board with the top ten usernames for that exercise.

Utilities will consist of written or aural exercises, and some of those exercises will require a guitar. So for example there could be a utility that tests a student on their ability to identify the root note of a jam track. There could be a utility to spell seventh chords or modes. And there could be a utility to play along with a mode and identify its modality or tonality.

For languages I’m using PHP, mainly because I sort of know it. I’m licensing all the code under GPLv2 so nobody steals my amateur PHP scripts :). I’ve wanted to build a music education website – for some time now. And I’ve planned everything out and I’ve just realized that I can build most of my ideas now. When I create them I can try to get feedback which is very valuable.

The site doesn’t have to be written in the hippest technologies of the day. The goal is to try to develop something interactive that allows musicians to learn. And to take feedback from people who use it on how it could be better.

The goal will be to mix theory with playing.



]]> 0
A Late New Year’s Resolution for 2018: Learn WordPress Thu, 29 Mar 2018 02:03:49 +0000 My goal for 2018 is to learn WordPress. I have to admit when I fist heard of WordPress I kind of looked down on it. I wasn’t the best dev, I surely didn’t consider myself a dev. That said a WordPress developer sounded like an oxymoron. Those people used software to build websites. The only software I needed was PHP Storm. It was only later when people on Experts Exchange recommended WordPress for some of my projects that I decided to check it out.

As you can probably tell, I’m not very fluent in WordPress. This site uses a free theme. Customization is minimal. When I purchased this domain I was going to simply have a static HTML page with my resume on it. When I started playing around with WordPress I saw how it could be useful for some things. I learned how to install it from the GNU/Linux command line and started playing around with it.

I want to start a web dev hosting company to pay the rent in College. WordPress is a great tool to use for clients. To begin with, you can create something of value for a low cost in time which results in a low cost in money. You can use a theme and customize it. If the client wants a custom theme it allows you to do that too. Best of all, clients can customize their websites without having to call me.

Another project I am considering is starting an e-commerce store to sell vapes and vape juices. I’ve been able to quit smoking using a Kangertech Top Box Mini. So with that goal I kind of narrowed it down between Woocommerce and Magento. I tried to install Magento last night but I couldn’t even get it working. I’m pretty fluent with Linux concepts but it requires some pretty advanced configuration. Using Woocommerce allows me to see if I can make money without investing an inordinate amount of time. It’s also WordPress, which I need to know for clients.

We’ll see how this year goes.


]]> 0