Welcome back! For part 2 I sat down yesterday afternoon and decided that I would get going on integrating wordpress and give it a shot since I eluded to it in my previous article.

With this change I have had a great experience, overall it took only a few hours and the issues I faced were usually my own from typo’s or something like that. I then spent some time cleaning things up a little, writing up my about page and generally getting everything into a stage I could start sharing this portfolio with people.

So let’s get started, firstly, I am using godaddy, so actually setting up WordPress was done by clicking WordPress in my cpanel and selecting to install the application.

Once I had this installed I noted the directory I placed this into. I then had a little perusal to re-familiarise myself with how it worked. Remembering how it seperates headers, footers and functions into their own php for themes. I want to keep my homebrewed/OTS theme and only really wanted wordpress for the backend part where I could easily write new articles rather than using notepad++ and coding it all. This is how I achieved that, firstly I needed a way to interface my frontend to the backend, we know from my first article that I used a REST based approach between PHP and jQuery to access a MySQL DB I had defined.

So imagine my glee when I found WordPress had a REST API interface. For much of the first hour though I found most of people’s online answers in stuff like stack overflow was outdated, you can’t install the API as a plugin since it’s been moved to the core. Since that change, the URL had changed also. Finally I found the right code snippet which showed the new URL: https://renemorozowich.com/using-wordpress-rest-api-get-blogs/

$response = wp_remote_get( 'https://www.sumydesigns.com/wp-json/wp/v2/posts?per_page=2' );

What was great about this code snippet is that it also included how to limit the number of posts returned, specifically only looking at the most recent. Sounds great right? Especially when you recall my first code snippet in Part 1, I mention how I would want to limit it when I have more articles written. Perfect!

And yes, for all my bah humbug attitude to WordPress before, I was pleasantly surprised. So the first page I began work on was article.php and started by creating a back up of course. One change I made was I embedded the content with PHP rather than with jQuery, I’m going to continue down this approach when I want the page to load with content immediately rather than dynamically as I’ve noticed some issues with loading in just that it loads the page, then loads the content sometime after which gives a dodgy user experience.

  <!-- Page Content -->
  <div class="container" id="container">
    <!-- /.row -->
    <!-- /.row -->
<?php
$check = 'http://www.edward-jones.co.uk/blog/wp-json/wp/v2/posts/' .  $_GET['id'];
$json = file_get_contents($check);
$p = json_decode($json);
    echo $p->content->rendered;
?>
<p><p>
  </div>
  <!-- /.container -->

So as you can see, fairly simples! But took a while to find that link to use, thank you to the author! Next I got started on the category.php page, here I had a few things to keep in mind, firstly that I might want to display all articles if no category id was set. We’ll start in the same section (container) and I did this via:

 <!-- Page Content -->
  <div class="container" id="container">
          <?php
           if(isset($_GET['id'])){
$json = file_get_contents('http://www.edward-jones.co.uk/blog/wp-json/wp/v2/posts?categories=' . $_GET['id']);
           }else{
$json = file_get_contents('http://www.edward-jones.co.uk/blog/wp-json/wp/v2/posts');
}

Now I had my json request, I needed to change the jquery style of appending into the html to php simply echo’ing it out. One thing that caught me out for a long while was my assumption you could add strings together by + when actually in PHP it’s a comma. Once I wrapped my head around this I came up with the code:

$posts = json_decode($json);
foreach ($posts as $p) {
    echo '<div class="row"><div class="col-md-8 mb-5">';
    echo "<h2>", $p->title->rendered, "</h2>";
        echo "<hr>", $p->excerpt->rendered, '<p></p><a class="btn btn-primary btn-lg" href="article.php?id=', $p->id, '">Read More &raquo;</a></div>';
            echo '<div class="col-md-4 mb-5">';
    echo '<h2>&zwnj;</h2><hr><img class="card-img-top" src="' . $p->featured_image->size_medium . '" alt="">';
    echo "</div>";
    echo '</div>';
}
?>
    <!-- /.row -->
    <!-- /.row -->
  </div>
  <!-- /.container -->

A new change you might notice is the inclusion of a featured image for my page. I actually did this after fixing up the index page but let’s talk about it now and go page by page as we’re almost done. I have to thank for this both this article https://medium.com/@dalenguyen/how-to-get-featured-image-from-wordpress-rest-api-5e023b9896c6 as well as the tool Postman. It was great to crack out Postman again and use it for my troubleshooting. It served really well here because a lot of articles online say that it’s simply $post->title, when it wasn’t and threw errors or returned “Object”. No, postman showed me to go another level and get $post->title->rendered. There’s definitely been some big changes in newer WordPress versus most of the online content/documentation which needs updating.

Another addition was that mention I had before of having the possibility to see all articles, this was simply:

<!-- Header -->
  <header class="bg-primary py-5 mb-5">
    <div class="container h-100">
      <div class="row h-100 align-items-center">
        <div class="col-lg-12">
          <h1 class="display-4 text-white mt-5 mb-2"><?php if(isset($_GET['id'])){
          $json = file_get_contents("http://edward-jones.co.uk/blog/wp-json/wp/v2/categories/" . $_GET['id']);
          $cat = json_decode($json);
          echo $cat->name;
          }else{
              echo "All Articles";
          }?></h1>
          <p class="lead mb-5 text-white-50" id="desc"></p>
        </div>
      </div>
    </div>
  </header>

One other final thank you is that I couldn’t get my columns within my rows to match up, you’ll see the line with <h2>&zwnj</h2>. This is because it was the heading that was in the first column and so I used an invisible character I got from https://www.quora.com/How-do-you-insert-an-invisible-character-in-HTML.

One final mention to note here is that it was at this stage I changed the GET from getting name to id. We’ll address this later but it’s mainly because you can’t get category by name in wordpress so a change was forced. https://developer.wordpress.org/rest-api/reference/categories/

Great so that’s another page down, let’s crack on and finish up on my index page and then finalise on re-writing the menu. At this stage, I had my head around it all and noted that the JSON response I had built before had similarities with the WordPress REST API. So, I actually just modified a few things to make it fast and easy (I know, I said earlier I don’t like it loading dynamically! But It’s just so easy 🙂 ).

Here is also where I now could use that nice filter I mentioned before and specified to only return 3 posts, naturally WordPress would return the latest 3 so also solved that problem. So all I really had to do was change the URL of my request for the post cards on the index page and then a little around the json structure:

	<script>
	$(document).ready(function(){
	$.ajax({
							type: "GET",
							url: './blog/wp-json/wp/v2/posts?per_page=3',
							success: function(response)
							{
								var jsonData = response;
								for (let i = 0; i < jsonData.length; i++) {
								// user is logged in successfully in the back-end
								// let's redirect
									$('#cards').append('<div class="col-md-4 mb-5"><div class="card h-100"><img class="card-img-top" src="' + jsonData[i].featured_image.size_medium + '" alt=""><div class="card-body"><h4 class="card-title">' + jsonData[i].title.rendered + '</h4><p class="card-text">' + jsonData[i].excerpt.rendered.substring(0,100) + '...' + '</p></div><div class="card-footer"><a href="article.php?id=' + jsonData[i].id + '" class="btn btn-primary">Find Out More!</a></div></div></div>');
								}
						   }
					   });
	});
	</script>

So, that was nice and easy and postman came in handy once more. Now I had all my pages updated, there was just one thing left… the menu, right now, it kept sending GET as a name for categories which was wrong to do, as well as grabbing it from my old DB. So, here was where I noticed a big coding no no I did before. I had duplicated my code across each page rather than modularise and re-use this, woops! It was more a laziness to do it than anything else, so I quickly changed this to simply include a script file:

  <script src="./menu.js"></script>

After loading jQuery of course as that’s needed for menu.js to run. I replaced the previous code in each page with this include in the head section. Then using that page on WordPress categories referenced before, updated my jQuery code as follows:

	$(document).ready(function(){
	$.ajax({
							type: "GET",
							url: 'http://edward-jones.co.uk/blog/wp-json/wp/v2/categories',
							success: function(response)
							{
								var jsonData = response;
								// loop the outer array
								for (let i = 1; i < jsonData.length; i++) {
									//append to menu
									$('#projects').append('<a class="dropdown-item" href="category.php?id=' + jsonData[i].id + '">' + jsonData[i].name + '</a>');
								}
						   }
					   });
	});

You may notice I started i at 1, this is because i=0 is the “Uncategorised” category which I can’t delete and don’t want to display, so I simply skip it.

And that’s it! WordPress fully working and incorporated now with links leading where they should.


My next article will be fairly tedious (sorry), I’m going to be running through several issues I had to fix up, some because I want to support lower resolution computers as well as phones, some from dynamically loading pages and others just because I wanted to add it in.

To be covered in the next article:

  • Code width fixes
  • Footer fixing
  • Image widths
  • Contact Us page fixes
  • About page with “Core Values”
  • Move index card loading to PHP from jQuery

Leave a Reply

All fields marked with an asterisk (*) are required