Jonnie Grieve Digital Media: Website Blog.

Archived Posts: PHP Archives – Jonnie Grieve Digital Media posts.

Websites and interacting with databases.

So in recent weeks my learning attention has switched from Java to PHP.

When I was doing my HNC (Higher National Certificate), a couple of years before I started my degree I was faced with a challenging individual project. It was a very difficult time and a crossroads in my academic life. I faced failure and learning how to pick myself up again. The project I spoke of involved learning how to connect a website to a database.

During my project. I had a project tutor. Every week he would ask me about something called a “confidence test” which was a very particular particular process referring to making a successful connection to a database.  I did try but I could never manage it. And it transpired I was trying to do something I had no experience in doing from my course.

In the project I ended up doing have to attempt in the end and bizarrely, it was the only module I ended up passing in my HNC but I failed that year. I had to take that hit and try again the next year.

Fast forward nearly a decade and I did pass my HNC in the end; I did go on to get a Higher National Diploma; I did get my degree.  And I have gone onto tackle database connections again. This time I have made successful connections and my “confidence” in that regard has increased.

I am now learning how to create webpages that interact with databases in different ways. creating records, reading data, updating those records and deleting them. In other words all the basic interactions with data that fall under the term CRUD. Create, Read, Update, Delete.

Today, with a bit of painstaking research I solved a major problem that was holding my back in a small personal development project.

I was so sure that I was following the video tutorial to the letter but there was just one or 2 little differences in my code that caused the bugs.

Imagine a simple web page with a drop down box, which is a form element and a button that is going to bring up a report based on data that lives in a database.  There was a problem in that no data was being return but I kept getting this PHP notice on the page.

So somewhere along the line not all the data, (or none of the data at all was being retrieved and passed to the function. Eventually I traced the issue to 2 small typos.

The first thing was I needed include the colon in my first echo string for the option value. I’m not sure what makes that work but I think it’s something to do with the query string. Not having it meant a property wasn’t carried over causing the offset warning.


So now when I tested the form I was getting this query string in the URL.

But having solved one problem, it seemed report wasn’t generating any tasks or totals when I tested the drop down. With a keen eye, I noticed that the query string wasn’t carrying a last number in the URL; the number identifying an individual record which is a project ID.

I traced the problem to the same function. One of the things about working with soft and hard quotes is knowing when to use them and in what combination. It seems like I trying to apply a hard quote into the reference to the project ID even though this was concatenated in.

So another day passed and a new learning experience. Now, database connections aren’t such a mystery and are not so daunting. Hopefully I’m going to learn a few more things about CRUD too.

New project: Object Oriented PHP

I uploaded a new project to my portfolio earlier today. This is a project I’ve been working on for a little while in my attempts to get to grips with Object Oriented Programming in PHP.

I followed a Treehouse course which teaches how to use Objects in PHP create an online Cookbook. As I built the file I saw the potential to branch out the work into a set of web pages.

  • Homepage
  • Cookbook
  • Meal Plan
  • Shopping List
  • And a request page to include more recipes.

Rather than hard coding the content in HTML it is stored in PHP files, included into the project via PHP and generated once in a special PHP file across many pages.

Say for example I want to look at the required shopping list all for the recipes in the cookbook.

By simply going into shoppinglist.php I can see how this is rendered.

echo Render::listShopping($cookbook->getCombinedIngredients() );

FirstRender class from render in which the listShopping method is contained. The instances of another class through the cookbook variable which then calls the method from the RecipeCollection class.

The three main files that make up the process are

recipes.php – the files that create Objects that store the raw data that contains the information for the recipes.

render.php – contains a separate php class that contains methods for displaying recipe data to the browser.

recipe-collection – the getter and setter methods that retrieve methods and set values so they can later be run.

Much of what I have done remains a blur. I’ve never hidden the fact that I don’t have a natural programming brain. But I do think I’ve stood myself in good stead by spending time building this project. I’ve organised it in such as way as the flow of the program is easily traceable.

Making a WordPress Theme #3

The third stage of making a WordPress Theme I wanted to concentrate on is Widgets; and it is trickiest area to work with to date. Not in terms of the technicalities of making WordPress recognise widget areas, but of simply finding a place for the widget to go. Because at the time I didn’t know if I wanted widget areas in my theme I didn’t think so far ahead as to prepare a widget area in my static theme. For the most part, I planned for the site will be free of widget areas visually but I did find I wanted a couple of widgets in the top and bottom of my blog content i.e. the home.php template. In terms of finding getting widgets to work it is quite straight forward.

The basic process is as follows

  1. Create a widget area in functions.php
  2. Find a place in your templates for the widget to actually go.

As a WordPress Developer, you are in complete control of where your widgets appear. This is how I did it for my theme.

“Hello WordPress, I’m adding a widget area to this theme”

There are 2 main functions that WordPress uses to create Widget areas. These are create_widget and inside it, register_sidebar. Sidebar is WordPress speak for a widget area. I suspect, although I’ve not researched it, that’s simply a throwback to early days WordPress terminology.

What happens here is that  an array of objects by using some parameters.   These control the name. id and the description of the widget area; so customisable strings that describe the widget and what it will do.

The ID key doesn’t go in the admin area.  It is merely a unique identifier for the individual widget.  This is the id or slug that WordPress will use to distinguish it from another.

Then the function is then called and the values for the parameters passed in. You’d then see this values in the Widgets page of the admin area. That’s all you need to make the widget area appear in the admin area. There are a few other customisable options such as using dynamic HTML classes as containers for your widgets but these are optional.

Once added, all the widgets are available and can be dragged into the widget areas via admin area.  But much like we did with the menu area for WordPress, all we’ve really done is let WordPress know that a widget area exists.  The next stage is to let WordPress know where in the template it is.

Now WordPress, here’s the place for my widget

WordPress uses a specific template file for widgets that is used to store the widget markup. So this is where the building blocks of the widget will go.

We generate a widget by first checking that a widget with a certain id exists. If it doesn’t we generate some markup telling us that there is a problem. But if everything does work we should see the widgets below.

wordpress-widgets

How did I get it there?

I carefully placed  a function call anywhere in the desired template file to finally display the widget.  I used a WordPress function called get_sidebar that directly called the sidebar.php function.

That is how to use the function in its simplest form.  And that’s all that is needed to display the widget in this case. But there are a couple of issues regarding using the function I think are worth talking about.

First of all, if you wanted to retrieve a widget that’s been given a particular id you simply pass in that widget id as a string.

Whereas

will call the contents of sidebar.php you can also pass in a string like this.

Currently all I have is the sidebar.php that has my widget, because that is the widget with the id of blog, but if I put it in its own template such as sidebar-blog. So if “blog” was the ID of the widget, WordPress would call that template file sidebar-blog.php.

The second point is that if you’re using get_sidebar() function it can only be called once. For example if you were to have a function call at the bottom of the template and another at the top then only the one at the top will work.

There is however a work around that I utilised to show 2 copies of the same widget.

I went into my home.php template and first used the standard WordPress function to call the widget and the top and secondly called the sidebar.php file directly rather than using a function. I called it using an include, using a path to the template folder and the adding the file as a string argument. This was the result.

 

wordpress-widgets-2

Conclusion: What’s next?

So now I have my design, navigation, blog and widgets set up for my theme.

But there’s still some work that can be done with the blog. At the moment, it only displays a certain amount of posts, there’s no pagination or anything that indicates that the blog looks like a WordPress blog.  That needs changing, and this is what I’ll focus on next.

Making a WordPress Theme #2

By this point, we’ve linked the CSS and JS files and created default WordPress templates so the website takes some semblance of shape.

The problem is it is empty of content and, depending on what text has been entered into the admin area via pages and posts and there’s no means of getting around the site. No links.

But we can’t just display static data on a WordPress site. In order to update content and make sure changes we make to our content update on the website, it must be pulled in dynamically via the WordPress Loop.

But there’s a little more to it than that. We also have to dynamically pull in other pieces of content too, such as the website title and any permalinks so that pages link together correctly. Basically, any content that changes from page to page needs a WordPress function or a custom function to show the appropriate content.

Before we go into the WordPress loop, I’ll explain some of these functions.

Pulling in Dynamic Content

Remember now that all the design work is contained in php template files. That is how WordPress Works and unique content is generated in the admin area via Pages and Posts.

But there are smaller functions that echo out content sni  ppers outside the scope of the WordPress loop.

In header.php common ones are

wp_title();
wp_head();
bloginfo();

As we go through the markup there are certain things that need to be changed. Otherwise the same data will be displayed each time header.php and footer.php are called. So instead of static text inside for example the title tag. wp_title() is used, inside a separate PHP block.

Example: header.php
<!doctype html>
<head>
<title><?php wp_title(); ?></title>
<?php wp_head(); ?>
</head>

wp_head() is a small piece of code that accomplishes a lot of tasks. It is this function that is responsible for enqueing the files we linked to in the functions.php file. All the styling, all the functionality via the javascript, if we didn’t have wp_head(); none of this would work.

<a href=”<?php bloginfo(‘url’); ?>”>
<img src = “<?php bloginfo(‘template_url’); ?>/img/jgdmLogo.png” id = “jgdmLogo” alt = “<?php bloginfo(‘name’); ?>
An independent web design business covering North East England and Beyond” />
</a>

the bloginfo(); function takes specific parameters as strings e.g. url, name and description, in order to display content to the screen. Another parameter, “template_url” is an argument that grabs the path to the template directory, wherever that lives of your WordPress installation. It can be used to generate a path to an image file that hasn’t been uploaded via the WordPress admin area.

<?php bloginfo(‘url’); ?>
<?php bloginfo(‘template_url’); ?>
<?php bloginfo(‘name’); ?>
<?php bloginfo(‘description’); ?>
Example: footer.php
<?php echo date(‘Y’); ?> – dynamically load copyright data.
<?php wp_footer(); ?> – loads wp menu bar

In this example there are 2 key functions that generate unique content. date() with a parameter displays a dynamically date to the screen based on a certain timestamp.

wp_footer(); works in a similar way to wp_head(). It will enqueue any files set in functions.php to loading the footer of the code as well as the JavaScript files that load the WordPress menu bar.

The WordPress Loop

In order to get the main content for any WordPress website the WordPress loop must be used. It can be used in one or two ways but the format below is in my opinion is the simplest;

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<!– content –>
<?php endwhile; else : ?>
//alternative text if no posts found.
<p><?php _e( ‘Sorry, no posts matched your criteria.’ ); ?></p>
<?php endif; ?>

This performs a simple check to see if there is content to be found and to display the text while there is content. It only needs to be used once because WordPress is smart enough to know which content is assigned to which permalink.

So that’s the syntax. Let me post my example of how the loop is used.

<section class = “mainContent”>
<article class=”content-area”>

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>

<?php endwhile; else : ?>
<!– –>
<p>Sorry, found no content.</p>
<?php endif; ?>

First you have your opening HTML markup that your CSS will select. It’s important to get this right because there’s no facility in the admin area to affect how the text displays in the admin area, beyond the controls in the text editor. For absolute control you use CSS.

The first line of PHP checks for content from the admin area but doesn’t display it. To display the content we need at the very least a WordPress function called the_content(); This will echo out the text typed into the Admin area text editor. It will generate markup that can be picked up by CSS.

The rest of it is simply closing out the while and if portions of the loop.

Hooking in the Navigation

The WordPress loop pulls in content for all individual pages and posts of your website. Unfortunately it doesn’t do a single thing for displaying your navigation. It’s completely separate to it.

Fortunately, hooking up your websites navigation is fairly straight forward. I’ll go through the steps.

First, in functions.php we need to add support for menus to WordPress because it is not available by default. This is as simple as writing the following below.

<?php add_theme_support($feature, $arguments); ?>

$feature is a list of strings which add certain features. In this example we need to add ‘menus’s as a string parameter. $arguments is optional parameter.  Now, WordPress knows that you want to add a navigation area to your website.

The next thing we need do is let WordPress know that there exists in this theme one or more menus. This is stored as an array in the function register_nav_menus which is in itself stored in a function.

function register_theme_menus() {
register_nav_menus(
array(
‘primary-menu’ => __(‘Primary Menu’)
)
);
}

We then give this a function call the WordPress way making sure we do so whenever the page is loaded.

//when wordpress is initialising, call the above function
add_action(‘init’, ‘register_theme_menus’);

Finally we then find a specific location in our theme template for this menu to do. This is a skill in WordPress because you’ll have a specific format in your static markup and certain CSS styling.

<?php
$defaults = array(
‘container’ => false,
‘theme_location’ => ‘primary-menu’,
‘menu_class’ => ‘nav-collapse’,
);

wp_nav_menu($defaults);
?>

In my example I struggled for longer than I’d care to admit for how to get this to properly style in a WordPress template. It was in the right location but not all of the styling was being picked up. Further complicated by the fact I was trying to use a specific class that was used with a jQuery file.

Eventually I just did this

<nav class = “nav-collapse main-nav”>
<aside class=”hamburger”><img src=”<?php bloginfo(‘template_url’) ?> img/menu.png” /></aside>

<?php

$menu_args = array(
‘container’ => false,
‘theme_location’ => ‘primary-menu’,
‘menu_id’ => ‘navLinks’

);

wp_nav_menu($menu_args);
?>

</nav>

I wrapped the php function in HTML markup (why did I not do this before) and the problems disappeared. I let the markup do the work and in an instant, the navigation was there. Just as I wanted it.

Summary

So now I have a fully functional theme. I have my navigation working. I have one page that will pull in blog posts and the rest of my pages run from the page.php template meaning they display the right content for the appropriate page.

As I write this (14th March 2016) to I could deploy the website now if I wanted. But there’s a bit more to developing a WordPress theme. On my mind at the moment is how I can use and display WordPress widgets. That’ll be my focus in my next blog.

Making my WordPress Theme – Part 1

To kick off my blog which is now integrated into the WordPresss theme of my new website, I wanted to document the process of designing and building the theme that WordPress uses on this website today. This series of blogs is a month in the making but the details and processes of the site are still fresh and relevant today.

Incidentally regrettably the blog is best viewed on a desktop or tablet screen at the moment although I’m doing my best to fix this.

Making a start building a WordPress Theme.

It was good to finally get started recently on building a WordPress Theme for my website. Which will mean finally migrating this blog away from WordPress.com over to WordPress.org. This is beneficial as it gives me the perfect platform to add fresh and hopefully engaging content to my website regularly.

I love WordPress and I’ve thoroughly enjoyed learning it so far. As I initially started to write this blog I’d set the design on the WordPress theme on localhost. The CSS is set up and while I haven’t verified it because the navigation isn’t set up just yet, I’m sure the JavaScript is too.

There are doubtless plenty of articles on tutorials on how a theme is together up to this stage. Regardless I wanted to document how I did it and this is what this series of 5 blogs will concentrate on.

Once you get used to how the WordPress loop works and Template Hierarchy, you realise that putting a theme together is a much less daunting prospect than you may have first thought, certainly to begin with.

Here’s how I got started.

1. Download a new installation of WordPress on localhost

This requires a new theme folder inside which is a functions.php, style.css file, index.php and a screenshot file to identify the new theme in the WordPress admin area.

wordpress-ss-1

Once you have these files set up, in a theme folder that you generate; that is the directory, screenshot image, and a minimum of an index.php file and stylesheet, you have all you need to let WordPress theme to be activated. You’re good to go ahead select and activate your theme in the admin area.

2. Set up header and footer files

Add new files to control the template parts for the header and the footer of the website. These will be header.php and footer.php. These are the parts of the website that will not change so they will generally include the website logo, social media links, common links and the website navigation.

The first way to get WordPress to recognise the files is to include a dynamic link to them in the index.php file.

<?php get_header(); ?>

<p>Index.php</p>

<?php get_footer(); ?>

If you put some test content into the files, such as a paragraph element, and they show up on the screen you know that the files are properly linked.

Header

Index

Footer

index.php

And there it is.  You can see that the contents of index.php, footer.php and header.php are being loaded and displayed in the browser.

3. Working with the functions.php file.

So now that we know the header and footer files are working, the next thing to do is to “port” over the HTML and CSS content. The markup of course goes directly in those 2 files but for linking the CSS and JavaScript files there a WordPress function used to make sure they’re properly linked.

This like most other functions are placed in the functions.php file for your WordPress theme. If there is a customization or a change you want to make to the front or the back end of the website it will be placed in this file.

function jgdm_stylesheets() {
wp_enqueue_style(‘file_handle’, get_template_directory_uri() . ‘css/foundations.css’);
}

The file handle is a unique identifier for the individual file that is being enqueued and is used to hook the function into something called a “filter” that performs the queuing into WordPress. It’s the WordPress equivalent of a function call.

get_template_directory_uri() is a function used as an argument to dynamically grab the path to the image or media file.

//function to enqueue styles for the theme. function
jgdm_javascripts() {
wp_enqueue_script(‘responsive_js’, get_template_directory_uri() . ‘js/responsive.js’, array(‘jquery’),”, false);
}

This performs the same process as the *jgdm_stylesheets* function but it’s a little more involved as there are a few more required parameters to the function.

What do these parameters mean?

There’s the file handle, template directory function and final path as before. Then the final parameters are as follows.

The third parameter is an array of dependants for js files. The dependent might be jQuery in itself or another JavaScript file.

The next parameter is optional – version number of enqueued file (optional)

The final parameter is the location of file path in front end be it the header or footer. It takes a boolean value; True to appear in footer, false for header.

4. Hooking up the markup.

There’s little evidence at this stage to suggest the enqueue functions have yet worked, beyond checking the source code and your browsers development tools.

So it’s time to start putting the markup from the static web files into your WordPress php files. The main files to change are your index, header and footer files.

This is a crucial stage where it takes some practice and experience to learn where to put the correct markup. The static markup will be replaced in part with dynamic php code snippets and functions and eventually the WordPress loop.

In header.php you would place the main HTML for your navigation, logo and common styles and elements that come before the WordPress loop. In my example, I have a body element and a div element that are not closed. They will be closed in the footer.php file and WordPress will recognise this as correctly used HTML markup.

header.php

<!doctype html>
<head>
<title>
<?php wp_title(); ?></title>
<?php wp_head(); ?> </head>

<body>

Furthermore in footer.php, any closing markup is included along with any code for a website footer.

<footer id = “mainFooter”> <p>&copy; Jonnie Grieve Digital Media <?php echo date(‘Y’); ?> Designed by Jonathan Grieve</p>
<br /> <!– <span class = “footerLinks”>
<a class = “footer” href = “#aboutAnchor”>About</a>
<a class = “footer” href = “#clientsAnchor”>Clients</a>
<a class = “footer” href = “#hireAnchor”>Hire Me</a>
<a class = “footer” href = “#webAnchor”>Web Design</a>
<a class = “footer” href = “#flashAnchor”>Flash Design</a>
<a class = “footer” href = “#aniAnchor”>Animation</a>
<a class = “footer” href = “#psAnchor”>Photoshop</a>
</span> –> </footer>

<?php wp_footer(); ?>

</body> </html>

In addition you may have noticed 2 other pieces of code I hadn’t mentioned previously. <?php wp_head(); ?> and<?php wp_footer(); ?>

The functions serve 2 purposes. They pull in the enqueue functions we saw earlier but the wp_footer() is the code that pulls in the admin bar and all the JavaScript that powers it. So if you’re logged in to your WordPress site this will now show up on the front end.

Summing up

By now if everything has been set up correctly we should be seeing the website starting to take shape. The CSS should be appearing, any JavaScript will be set up. But no content is as yet being pulled in dynamically.

wordpress-ss-3

But I’ll leave it there for now and explain how to do just that in the next blog. This will include the different php functions that display all the pages and posts content and how this works together with the famous WordPress Loop.