PHP on Speckyboy Design Magazine https://speckyboy.com/topic/php/ Resources & Inspiration for Creatives Sun, 16 Feb 2025 20:47:02 +0000 en-US hourly 1 https://speckyboy.com/wp-content/uploads/2024/03/cropped-sdm-favicon-32x32.png PHP on Speckyboy Design Magazine https://speckyboy.com/topic/php/ 32 32 How to Display Content Based on WordPress User Roles https://speckyboy.com/display-content-wordpress-user-roles/ https://speckyboy.com/display-content-wordpress-user-roles/#respond Wed, 16 Oct 2024 06:16:30 +0000 https://speckyboy.com/?p=103643 Using the current_user_can function, learn how to display custom content and special features based on the roles and capabilities of your WordPress users.

The post How to Display Content Based on WordPress User Roles appeared first on Speckyboy Design Magazine.

]]>
When building a WordPress website, it’s often useful to provide content or functionality based on a user’s role or capabilities. For example, you may want to display some special content on your site – but only for administrators. That’s just one of many possibilities.

It’s quite handy that WordPress has a built-in function to help. The current_user_can() function allows you to check the permissions of logged-in users. Based on that information, you can provide them with whatever special goodies you like. Conversely, you can also turn off certain items as well.

Keeping with the previously mentioned special content example, we’ll dive into a few basic snippets that let us add this functionality.

Example 1: Administrators Only

In this example, we’ll check to see if the logged-in user visiting our page is a site administrator. If they are, a little welcome message will be displayed.

Before we go into the code, it’s worth noting that there is more than one way to check a user’s permissions. The WordPress Codex states that we can provide an existing user role inside the current_user_can() function, however, it’s not recommended. There could be inaccuracies that lead to the wrong thing taking place.

Instead, we can use the capabilities of that particular user role. There’s a complete list of what capabilities each user role has in the Codex. So, rather than check if the user is an administrator, we can check if they have a specific capability, such as activating plugins.

Now, let’s see some code. The following would appear within the theme template of your choice.

<?php
if ( current_user_can( 'activate_plugins' ) ): // check for a capability that only admins have ?>

          <p>Howdy, Administrator!</p>

<?php endif; // end of user capability check ?>

In this case, we’re checking to see if the user is able to activate plugins – something only administrators (and, on multisite installs, super administrators) have the ability to do.

 

Example 2: Let’s Get Personal with Members

While the first example displayed a generic message, we can also create a more personalized experience. This is especially important if you’re running a membership site. It helps to build that extra sense of community.

Here, we’ll add a personal message including the user’s first name. We can tap into this information via the get_current_user() function. We’ll also assume that our members are assigned the role of subscriber within WordPress.

<?php
$current_user = wp_get_current_user(); // grab user info  from the database 

if ( current_user_can( 'read' ) ): // 'read' is the lowest  level capability ?>

          <p>Howdy, <?php echo $current_user->user_firstname; ?>! Thanks for being a part of our community.</p>

<?php endif; // end of user capability check ?>

Incidentally, the ability to read a post is the lowest level capability within WordPress. Therefore, it applies to every user level – not just subscribers. This just ensures that we haven’t left anybody out.

Beyond checking for the read capability, we’re also displaying the user’s first name in the message. However, there are more possibilities with regards to user data that could be added to the mix.

Example 3: A Custom Header, Based on User Capabilities

For our last example, let’s do something a little more dramatic. We’re going to serve up different theme headers, depending on what capabilities a user has.

Through the get_header() function, WordPress allows for the use of multiple header files. And displaying them based on user conditions can be very useful. For instance, a site’s member might benefit from a header that is highly personalized. Non-members could then see something more generic.

In our code, we’ll again check to see if our users have read capabilities. And we’ll also add an extra check to ensure that they are logged in, via is_user_logged_in() – just for good measure.

If you’re using this code in a project, it would replace <?php get_header(); ?> throughout your templates.

<?php
if ( current_user_can( 'read' ) && (is_user_logged_in)  ): // the user can both read posts and is logged in
?>

          <?php get_header( 'members' ); // load header-members.php for site members ?>

<?php else: ?>

          <?php get_header(); // the default header.php, for non-members ?>

<?php endif; // end of custom header conditional ?>

Above, we’re checking to see if the user has the right capabilities and that they are indeed logged in. If both items return as true, a custom header file is shown. Otherwise, our theme’s default header will be displayed.

An Opportunity to Do More for Users

The examples above are just little ways that we can improve the user experience. But there is also the potential to do so much more. Really, the only limitation is your own imagination!

So, the next time you build a WordPress site, look for ways to provide users with features based on their roles and capabilities. They’ll appreciate the effort and you’ll have built a more complete website.

The post How to Display Content Based on WordPress User Roles appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/display-content-wordpress-user-roles/feed/ 0
How to Handle Major Software Updates on Your Website https://speckyboy.com/website-major-software-change/ Sun, 13 Oct 2024 12:58:40 +0000 https://speckyboy.com/?p=166800 Updates to system software and site components mean extra work. Here are some tips for managing those software changes that may impact your website.

The post How to Handle Major Software Updates on Your Website appeared first on Speckyboy Design Magazine.

]]>
The web is in a constant state of change. What we build today will inevitably need to adapt tomorrow. And the challenge of keeping up is only growing.

Modern websites have multiple dependencies. They include everything from PHP, your content management system (CMS), to JavaScript libraries. Even the classic 5-page brochure site can’t escape their clutches.

None of these items are immune to change. Sometimes, those changes add extra work to our plates.

The situation presents a multitude of challenges for developers. We may need to refactor a feature’s code. Or go through an arduous manual testing process. Both involve a lot of time and money.

So, how do you carry out such an endeavor? Here are some tips for managing software changes that impact your website.

Assess the Impact of the Change

On the surface, some software changes may not seem so serious. For example, updating your WordPress install. It’s often a routine task – until it’s not.

Sometimes, a theme or plugin undergoes an overhaul. The new version could mean changes to your implementation. Thus, you won’t want to click the “update” button until you assess what’s happening.

You can learn a lot by reading documentation regarding the change. For example, a changelog may offer vital information.

Hopefully, you’ll gain a clearer picture of what steps you need to take. If not, it’s time to contact the developer or post in a support forum.

We’re also assuming you have intimate knowledge of your website. That includes an understanding of how the site was built – along with its dependencies.

What if you inherited the website from another developer? You may need to dig a little deeper to gauge the impact of an update.

Take time to assess the scope of software changes and what action you may need to take.

Create a Staging Environment for Testing

It’s always worth repeating: Don’t implement critical updates without testing. You run the risk of something breaking in the process. Not fun at all.

A staging environment will allow you to test without risk. It’s an exact copy of your website, hosted locally or on a remote server.

Think of a staging environment as a playground for experimentation. You can turn on debugging or install development tools to catch any errors. Plus, you can add and remove components like plugins or libraries.

You might make a mistake or two – but that’s OK. There’s always an opportunity to reverse your changes or start fresh.

A staging environment is perfect for process-oriented updates – like upgrading to a new version of PHP. You’ll have a separate space to investigate and repair each issue. Again, it’s not something you want to do on a production site.

Your web host may offer a staging option. That may be your best bet. Ideally, you’ll want to use a server configuration that is as close as possible to your production environment.

If that’s not possible, try to get as close as you can with a local install. Having a place to test is the most important thing.

A staging website allows you to test updates in a low-risk environment.

Take Notes as You Test

Some web hosts allow you to push your changes from staging to production. However, this isn’t always an option. Therefore, you’ll want to take notes during testing.

There are a lot of steps involved with software changes. For example, you may have implemented several code tweaks. A crucial item could easily get lost in the process. That might be a problem when it’s time to launch.

Having some project documentation on hand can be helpful. It will serve as a reference as you deploy any changes.

What should you include in your notes? Here are a few ideas:

  • A list of changed files;
  • Changed server or CMS settings;
  • Items (like plugins or libraries) that have been added or removed;

These examples are a starting point. Feel free to document anything you think is relevant to your project. You’ll be glad you took the initiative when looking back! This step lessens the chances of making a mistake.

Oh, and be sure to back up your site before making changes. That can be a lifesaver should something go awry.

Be sure to document any changes you make during testing.

Prepare for Launch

Now that you’ve tested (and taken good notes), it’s full speed ahead! Much of what happens next will depend on the scope of your project. However, there are a few best practices worth following.

The first is to schedule a time to make the required changes. Try to do so when user impact will be minimal. Be sure to give yourself enough time for deployment and testing. You’ll also want to alert any stakeholders of what’s happening.

Next, create a checklist of tasks. List each step of the process in order. It’s a simple thing – but handy for keeping track of progress.

Also, make sure you have access to everything you need. For example, you may need permission to overwrite files on the web server. Or the account details for a third-party provider.

And don’t forget about any two-factor authentication tied to client accounts. You may need to coordinate a time to gain access.

Once you’re fully prepared, you can move forward with confidence.

Take everything you've learned and prepare to launch the website changes.

Turn Big Changes into No Big Deal

Updates to system software and site components could mean extra work. It’s a staple of website maintenance. And you never know when something new will pop up.

Web designers need all the help they can get. As websites have more moving parts, so does the likelihood of something major coming along.

It may sound a bit scary – but do not worry! A solid process can simplify matters.

Assess your situation, test on a staging environment, and document your work. Prepare for the change as you would a job interview. When something comes up, you’ll be able to handle it gracefully.

The post How to Handle Major Software Updates on Your Website appeared first on Speckyboy Design Magazine.

]]>
Why Wrangling User Data in WordPress Can Be a Nightmare https://speckyboy.com/wrangling-user-data-in-wordpress/ https://speckyboy.com/wrangling-user-data-in-wordpress/#respond Thu, 10 Oct 2024 09:27:45 +0000 https://speckyboy.com/?p=118276 Every website we build has its own unique challenges. But the tools we use can help us tackle them head on. WordPress, and its never-ending ecosystem of plugins have helped...

The post Why Wrangling User Data in WordPress Can Be a Nightmare appeared first on Speckyboy Design Magazine.

]]>
Every website we build has its own unique challenges. But the tools we use can help us tackle them head on.

WordPress, and its never-ending ecosystem of plugins have helped web designers tame even the most difficult client requests. Pretty much everything we need is just click-and-go. And if it doesn’t exist, we can build it ourselves.

But for each of these solutions we implement, there is a hidden consequence. One that only rears its head when we dig a little deeper for user-specific data. Only then do we realize the tangled mess that sits beneath that pretty outer shell.

A Simple Start

In a default WordPress installation, user data (at least, the kind you might want to export) is actually pretty neat and tidy. Data is stored in the wp_usermeta database table. Inside, you’ll find the basics like the user’s name, along with their role/capabilities and their account preferences.

Combine this with what is in the wp_users table (username, email address, password), and you can grab a lot of useful information for every user on your website. Plus, you can easily import a CSV list of new users if need be.

Of course, most websites don’t stop at a default configuration. On the contrary, we often add any number of plugins so that users can do more with our site.

We want them to do things like have custom profile information, keep track of orders and belong to specific groups. Plus, features like forums, support portals and learning management systems are also widely used these days.

And that’s just scratching the surface. There’s a whole lot more that can be added to a typical WordPress site. That’s a good thing, until you have to try and wrangle the data.

WordPress User Meta Table.

Data, Data, Everywhere

The issue at hand is not so much the fault of WordPress itself. It’s that where a particular piece of data is stored is, in many cases, left up to plugin developers. That can result in the user data you want to gather being stored all over the place. It’s the nature of the beast.

Let’s use a recent website I worked on as an example. It uses a membership plugin, which allows people to join the client’s organization.

Collected Data

When they sign up, we ask them for more than just the standard WordPress user metadata. New members are asked for information such as:

  • Mailing address;
  • Phone number;
  • Their preference for how they receive newsletters (email or postal mail);

Generated Data

Beyond the information we ask users to supply, there is also a plethora of data generated by the membership plugin itself, including:

  • Membership status (active or inactive);
  • Membership level;
  • Membership expiration date;

There’s nothing over-the-top about the configuration. It’s probably not much different than the tens of thousands of other sites running the same membership suite.

While the site itself isn’t too complicated, that doesn’t mean its user data is easy to find. Let’s look at how a seemingly-simple task can become a time-consuming challenge.

HTML Code on a screen.

The Challenge

The client had a very basic need. They wanted an export of all active members who prefer a hard copy of the organization’s newsletter sent to them. Based on what we have, this should take just a few minutes to cobble together. I was way off.

This was much more difficult than I envisioned. The data we needed was right there in the database. But trying to piece it together proved to be a near-monumental task for someone who isn’t a database-querying wizard.

However, that’s why we have plugins, right? And there are a ton of different options – both free and premium. But, no matter what I tried, I couldn’t seem to get exactly what the export required. Here’s why:

  • The custom data we ask members to provide us is easy enough to get. It’s in the wp_usermeta table, which user export plugins are generally able to find. So, generating a list of users who wanted that hard copy of the newsletter was fairly straightforward.
  • The other member-related data, however, is stored in another table that is exclusive to the membership plugin. Even a rather robust commercial plugin I used couldn’t help me here.

The result was that I could find out who asked for the postal edition of the newsletter, but I couldn’t tell if their membership was active – not very helpful.

Sure, that info was stored in an adjacent table in the same database – but it may as well have been on Jupiter for my purposes. It felt like searching the house for your keys, only to find that your neighbor is holding them for ransom.

Eventually, I did find an export plugin – one that included an add-on for the membership plugin – that was able to help me put together the data I needed. If that hadn’t existed, I’d still be stuck with only a half-solution.

Person viewing a spreadsheet on a laptop computer.

Can the Experience Be Improved?

This all left me to wonder how these situations can be improved or avoided in the first place. It’s a tough call.

First, I admit that these types of challenges aren’t my strong point. Someone with plenty of expertise in PHP and MySQL could probably come up with a custom solution. Me? I’m left to experiment with plugins and groan when they don’t work as I’d hoped.

But one question worth asking is, should such expertise be required to export a complete set of user data? It seems like there should be a more user-friendly way to make this work.

The fact that WordPress allows plugins to create their own database tables is both understandable and even beneficial. It ensures that we can install and uninstall plugins without fear of breaking something.

Yet, while this all works seamlessly to the naked eye, it’s anything but to those of us trying to access the underlying data.

Perhaps there needs to be an API that allows us to grab everything related to a specific user, regardless of where it is stored in the database. But I’ll leave that discussion to those who know the pros and cons of such a feature.

Until then, I’ll just keep on piecing together things as clients need them – hoping for a much cleaner process in the future.

The post Why Wrangling User Data in WordPress Can Be a Nightmare appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/wrangling-user-data-in-wordpress/feed/ 0
10 Free Tutorials & Courses for Learning PHP https://speckyboy.com/php-tutorials-for-beginners/ https://speckyboy.com/php-tutorials-for-beginners/#comments Sat, 14 Sep 2024 16:49:01 +0000 http://speckyboy.com/?p=35889 PHP is easier to learn than most programming languages. But if you are new to it, it can be daunting. We can help with these PHP tutorials.

The post 10 Free Tutorials & Courses for Learning PHP appeared first on Speckyboy Design Magazine.

]]>
You have probably heard that PHP is much easier to learn than any other programming languages, such as Java or the .NET languages, not to mention Perl, but if you are new to PHP, it can be daunting. If you are new to PHP, we are here to help.

The first block of PHP tutorials are more general and covers the basics of PHP as a language, such as variables, conditionals, HTML forms, loops, arrays, strings, functions… While the second block of tutorials are all about performing a particular task, such as creating captchas, building forms, and even building a complete CMS.

Now remember, take your time with each tutorial and enjoy!

A Simple PHP Tutorial

It doesn’t matter what kind of information you are looking for, it is always best to start at the source. This, of course, applies to learning PHP as well, the very site of the PHP programming language: php.net.

I am not saying this tutorial is the easiest, but it is a great tutorial for getting started with. It is more like a general introduction to PHP than a complete guide. It is split into the following sections:

  • What do I need?
  • Your first PHP-enabled page
  • Something Useful
  • Dealing with Forms
  • Using old code with new versions of PHP
  • What’s next?

The tutorial should only take you about 15 minutes to complete – providing you don’t check all the hyperlinks to the other pages. If you do, it will probably take weeks to complete.

PHP for Beginners

This tutorial is a much longer and more in-depth that the tutorial above. It covers all the basics of PHP, such as variables, conditionals, HTML forms, loops, arrays, strings, functions, security, file manipulation, MySQL, user authentication. At the end of the tutorial you will find chapters on how to code sample apps, such as polls and online forums.

This is a long tutorial and you may have to go through some chapters more than once, especially if you are new to PHP. So, you will need at least a day or two to go through it all.

Introduction to PHP

If you are a fan of video tutorials, then you will love this PHP Course. There are over 200 videos available and they cover absolutely everything about PHP.

The series covers all aspects of PHP, such as how to install XAMMP, how to create your first PHP file, input/output, variables, conditionals, operators, loops, commonly-used functions, strings, arrays, sample applications, etc.

It’s a huge resource and if you want to learn absolutely everything, you will need weeks to cover it all. Each video is reasonably short, though – from 1 to 10 minutes, so you can watch a couple of them in a day, revise them on the next day, and thenmove onto the next video.

PHP 101: PHP For the Absolute Beginner

This is another complete PHP course that walks you through the basics. As with the other courses, it covers everything – variables, operators, loops, functions, arguments, MySQL, object oriented programming, sessions and cookies, error handling and security.

It even includes two tutorials for building sample applications – such as a simple web application and an RSS news aggregator. Similarly to the other complete courses, this one will take at least a couple of days to read, learn, and revise.

MySQL PHP Tutorial

The tutorials so far include sections on MySQL and how to use it with PHP, but since PHP and MySQL are used together [almost] all the time, it wouldn’t hurt to cover a tutorial that focuses solely on MySQL.

This tutorial explains how to create a new MySQL database, connect to it, create users and give them permissions, write a simple script, create and populate a database, retrieve data, escape characters, print column headers, count fields and rows, write and read images, and use transactions.

If you are already familiar with the SQL syntax this tutorial should only take you 2-4 hours.

List Files & Directories with PHP

Lists of files and directories are very common in web development. This tutorial will show you how to list files and directories with the glob() function, a combination of the opendir(), readdir() and closedir() functions, and the scandir() function.

You will also learn some advanced file/directory listing techniques – SPL iterators, such as the FilesystemIterator, the RecursiveDirectoryIterator, and the GlobIterator.

The tutorial isn’t as complex as it might at first seem, but you probably should budget at least 45 minutes to complete it. It could even take longer, if everything is not working as expected and you need to make some fixes.

Automatic CSS3 Prefixer & Compressor Tutorial

CSS files are text files but they can be very large. That is why they will benefit from some compression. Additionally, instead of writing all CSS3 properties with browser-specific prefixes by hand, this can be automated with PHP.

This tutorial will teach you exactly how to do this: Generate CSS3 properties with browser-specific prefixes, how to concatenate all the CSS files to save space and reduce load time, and how to do both automatically when a web page is requested.

The estimated time to complete the tutorial is about an hour.

Automatic CSS3 Prefixer and Compressor php Tutorial

Create Your Own Captcha in PHP

This short tutorial has been written in a typical programmer’s fashion, meaning it has little to no explanation, short to missing comments, and the assumption that everything is obvious and clear.

However, aside from this, it is a useful tutorial and the slightly more advanced programmers might love it just because it uses few words and plenty of code.

Getting Started with PHP Regular Expressions

And now a tutorial on everybody’s favorite: regular expressions. Unfortunately for everybody who hates them, regular expressions are pretty useful, though often you can bypass them with other techniques.

The tutorial in the link explains what regular expressions are, the Perl compatible regular expressions, the basic syntax of PHP regular expressions, how to use regular expressions in PHP, useful regex functions. Additionally, the tutorial includes a cheat sheet where all the basic stuff is gathered in one neat place.

The tutorial could take you an hour or two to complete but this depends on your familiarity with regular expressions. If you are a total stranger to them, expect to read some sections multiple times and, naturally, this will take you much more time.

Create Your Own Captcha in PHP tutorial

Simple Banner Rotator With PHP, jQuery & MySQL

This tutorial goes beyond PHP, but since in real life that is exactly what you need, that is why the tutorial is included here. First you need to create the database schema, then the XHTML code, then the CSS, and only after that you will move on to the PHP side of things.

The tutorial will take you at least 2 hours to complete, and that is if you don’t have to make a lot of modifications to the code.

Simple Banner Rotator With PHP tutorial

Build a CMS in an Afternoon with PHP & MySQL

If we are honest here, this tutorial will probably take you more than an afternoon to complete. Having said that, it also isn’t as hard as it seems.

In order to create the CMS, you do need to be familiar with the SQL syntax and MySQL, so if you do lack knowledge in these areas, first check the tutorials that teach MySQL above and then come back to this one.

The CMS you will be learning to build will have all of the basic features you would expect from a CMS.

The frontend will have:

  • Homepage with the 5 most recent articles
  • Article Listing Page (archives), where snippets of all articles are displayed
  • A “View Article” page (single post), where visitors can read the entire article

And, the backend will have:

  • Admin login/logout
  • List of all articles
  • Add a new article
  • Edit an existing article
  • Delete an existing article

PHP is fun, and it can be used for so many tasks. These tutorials won’t make you a PHP guru, but they will help improve your skills and hopefully allow you to develop more complex PHP applications.

The post 10 Free Tutorials & Courses for Learning PHP appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/php-tutorials-for-beginners/feed/ 3
The Web Has an Outdated Software Problem https://speckyboy.com/outdated-software-problem/ https://speckyboy.com/outdated-software-problem/#respond Tue, 21 Nov 2023 07:27:14 +0000 https://speckyboy.com/?p=143389 On the web, things don't go away so much as they fade into the background. As quickly as new tech arrives, the old continues to lumber along in the shadows.

The post The Web Has an Outdated Software Problem appeared first on Speckyboy Design Magazine.

]]>
Some might say that nothing lasts forever on the web. And that maybe change is the only constant. Favorite websites come and go, as do tools and technologies. Sure, there’s some truth to those statements – but it’s also more complicated.

You see, things don’t really go away so much as they fade into the background. The website that used to be buzzing with traffic might turn into a ghost town. And it’s just as likely that the technology behind that site is also sitting there collecting dust.

But it’s not just those old, unattended sites that have issues. There are also situations where a mission-critical website relies on outdated software. That could be anything from an abandoned WordPress plugin to an unsupported version of PHP.

It’s far from an ideal situation. And many potential problems can arise from sticking with these old standbys. Yet, it’s also the reality of the modern web. As quickly as new tech arrives to grab the spotlight, the old continues to lumber along in the shadows.

The problem is complex – and so are the potential solutions. Is it even possible to rid the web of these dinosaurs?

Why Do Websites Continue to Use Legacy Code?

When you picture a website that uses legacy code – what comes to mind? Maybe it’s a blog that hasn’t seen new content in a few years. Or a defunct online community. You might even think of a dormant business site.

The common thread of these examples is that they’re likely small and inexpensive (perhaps free) websites. Entities that are frozen in time.

Now consider a large enterprise site that is heavily customized. Maybe it includes bespoke functionality that enables customers to pay their bills. There could be a custom WordPress plugin that facilitates a specific workflow for team members.

Custom functionality is expensive and time-consuming to produce. And in some cases, it can be fragile. It might rely on a method or feature that isn’t supported in newer versions of its dependent software. For example, an application that was built for PHP 5 may no longer work in PHP 8.

And while a developer (or a team of them) can refactor the code – it’s not always easy or fits within a given budget. Much like the old stories of corporate users who kept Internet Explorer 6 around long after its time, legacy code can live on for years.

The bottom line is that outdated software very much remains in active use. That’s true at both the high and low ends of the scale.

 Outdated software is being run on both the high and low ends of the market.

Two Prime Examples: PHP and WordPress

Usage statistics change regularly – and they will undoubtedly shift after this article has been published. But two trends, in particular, are prime examples of outdated software in action: PHP and WordPress.

PHP 5 and 7 Are Still Out There

As of this writing, the latest version of PHP is 8.1. It was released in November 2021, and security updates are scheduled to end in November 2024. Version 8.0 was released in November 2020 (security updates end in November 2023). Version 7.4 was sent out into the world in November 2019 (security updates end in November 2022).

Thus, versions 8 and above have been with us for several years. Yet according to W3Techs’ PHP usage statistics, just over 6% of the sites surveyed are running PHP 8 or 8.1. Meanwhile, 70% are using some flavor of PHP 7, and nearly 23% are still running PHP 5 (which ended support in 2018).

The transition between major versions of PHP tends to be a slow one. That’s likely due in part to changes in compatibility. WordPress and its ecosystem, for example, have had a long road toward full support for PHP 8.

Plus, web hosts haven’t traditionally pushed customers too hard to upgrade (more on that in a bit). At the same time, website owners range from being unaware of PHP to not being overly concerned about upgrading.

In short: there has been little sense of urgency. Or, not enough of it to turn the tide and get more websites using the latest version.

PHP 8 adoption has been slow, according to W3Techs.

PHP version statistics from W3Techs, as of November 2022

WordPress 4 and 5 Live On

As we go to press (pun intended), WordPress 6.1 has been released. It’s the latest version of the most popular content management system (CMS) known to humankind.

And according to the W3Techs WordPress usage statistics, nearly 60% of surveyed sites are using version 6 or above. It’s significantly higher than the usage rates for PHP 8. That’s probably not too surprising, though.

By comparison, updating WordPress is easier and can even be automated. Site owners and those responsible for maintenance don’t necessarily have to lift a finger to upgrade. Managed hosting providers may also take care of it. And WordPress is known to value backward compatibility, so there’s less chance of a major issue occurring.

But outdated versions are still hanging in there. Version 5 powers 34% of installs, while over 6% of installs cling to version 4.

If there’s any good news, it’s that WordPress core continues to release security updates for several older versions of the software. Still, these sites lose out on new features and performance enhancements. Not to mention possible theme and plugin compatibility issues. Oh, and it’s unlikely they’ll work with the latest version of PHP.

It’s also worth noting that these statistics don’t account for websites running outdated or abandoned plugins and themes. That could be an entirely different galaxy worth exploring, yet just as relevant. This is where the majority of WordPress-related security issues originate.

 W3Techs notes that over 40% of WordPress installs are using versions 5 and below.

WordPress version statistics from W3Techs, as of November 2022

Why This Is a Concern

The term “outdated software” can conjure up all sorts of nightmare visions. A person shopping online with an unpatched version of Windows XP comes to mind. It might work, but there are a lot of risks in continuing to use it.

Security is of paramount concern. It stands to reason that using a version of PHP that is no longer receiving security updates is a risk. Attacks that might be easily stopped with newer versions could do damage to a legacy setup.

But so is employing an old JavaScript library or server utility with an open security flaw. Dependencies of all stripes can be dangerous, after all. The recent Log4j vulnerability is but one of many reminders.

Then there are issues of efficiency and performance. Outdated software that lacks these enhancements can negatively impact user experience, SEO, and energy consumption.

And the more outdated the software, the harder (and more expensive) it may be to get up to speed in the future. Each subsequent version can add obstacles to the process.

Outdated software poses a security risk.

Some Web Hosts Are Forcing the Issue

Web hosts have a role to play in helping their customers implement new software. And some are becoming more aggressive in these efforts.

PHP has been a primary target. Some hosts will allow customers to continue running an unsupported version but have begun charging an extra fee. This could be a result of higher support costs for customers using outdated software. At the very least, it’s a way to convince users to upgrade.

Still, others have taken a more hardline stance. They’ll notify customers that use an outdated PHP version and provide them with a scheduled upgrade date. From there, the site is upgraded regardless of whether it has been tested or patched for the new version.

It remains to be seen how effective these measures will be. But cleaning up outdated software is a massive undertaking. Thus, someone must get the ball rolling. Hosts are well-positioned to do so.

 Web hosts are warning users that use outdated versions of PHP.

Out with the Old?

At 30+ years old, the web has hosted an incalculable amount of software. Consider all the apps – large and small – that have been downloaded and installed on servers over time. It’s no wonder that some were left in place well past their expiration date.

Sometimes this legacy code sticks around out of necessity – other applications depend on it. But it might also happen simply because a site’s owner isn’t aware of the situation. No one may have approached them regarding an upgrade.

In either case, resources are what’s needed to increase modernization efforts. At the enterprise level, this means dedicated time and money to keep things evolving with newer versions.

On the lower rungs of the ladder, education is a key factor. Web hosts are starting to realize the importance of keeping customers informed. And web designers should do the same.

It starts by letting clients know where they stand, the dangers of using outdated software, and the benefits of upgrading. From there, they can make informed decisions.

No, a single upgraded site won’t change the world. But each is a tiny step towards a safer web that can take advantage of the latest technologies.

The post The Web Has an Outdated Software Problem appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/outdated-software-problem/feed/ 0
Automating Laravel Tests with Buddy Sponsored https://speckyboy.com/automating-laravel-tests-with-buddy/ https://speckyboy.com/automating-laravel-tests-with-buddy/#respond Fri, 02 Oct 2020 22:07:52 +0000 https://speckyboy.com/?p=114163 If you’re building web applications, it’s quite likely that you’ve heard of Laravel. It’s a popular PHP framework that streamlines the development process and includes its own, developer-friendly syntax. In...

The post Automating Laravel Tests with Buddy <span class="sponsored_text">Sponsored</span> appeared first on Speckyboy Design Magazine.

]]>
If you’re building web applications, it’s quite likely that you’ve heard of Laravel. It’s a popular PHP framework that streamlines the development process and includes its own, developer-friendly syntax. In addition, there are a number of premade modules available that can help you tackle tasks such as server deployment, debugging and cloud computing. And that’s just scratching the surface.

On its own, Laravel simplifies application development quite a bit. But it still takes a lot of time to get things right. Today, we’ll introduce you to Buddy, an automation platform that works in conjunction with Laravel and will greatly improve your workflow.

And, oh yeah, it saves you a ton of time. In fact, Buddy’s own measurements show that users deploy an average of 46 more times than those without automation, and seven more among those who use other CI/CD (Continuous Integration / Continuous Delivery) tools. Not only that, but a single developer saves an average of 37 minutes a day.

Use Case: Automatically Trigger Application Testing

Now, it’s time to see how Buddy can turn Laravel application testing into an automated process. But first, let’s set the scene.

Assumptions

First, we’ll assume that you have some knowledge of how Laravel works. If you don’t know much about Laravel and want to learn – not to worry. There’s a helpful resource to get you started.

Next, we will also assume that you have a Laravel application that you want to test. If you’re looking for an example, check out this guide on Buddy’s site, which features a calculator app.

Now that we have that out of the way, let’s start automating!

A Better Way to Test

Testing is a vital part of application development. Unfortunately, it can also become quite tedious. Manually running tests after each and every change bogs down the process. This is where automation can step in and increase efficiency.

Using Buddy, each type of Laravel testing method (see them below) can be fully automated to run at a time or situation of your choosing. You have a lot of flexibility with regards to what tasks you run and when you run them.

For example, you might want to trigger a specific set of tests to run whenever you push changes to a repository. This is exactly the type of thing Buddy was built to do. Simply write your testing scripts, include them in your repository and Buddy will run them automatically. That’s all there is to it.

Of course, you could spend hours writing some automation scripts to achieve the same thing. However, with Buddy, you’ll knock this out in just a few clicks. Just watch:

In addition to saving you time, this type of workflow also provides peace of mind. You no longer need to remember to test after each and every push – Buddy takes care of it for you.

Types of Testing

Buddy supports all types of testing, including unit tests, feature tests and browser tests:

  • Unit Tests: Used for checking small snippets of code, such as an individual method. Example »
  • Feature Tests: This type of test will look at larger collections of code, such as a website. Example »
  • Browser Tests: As the name suggests, this launches a browser and interacts with website content. Learn More »

*Note that the examples use the aforementioned calculator app as a reference.

Make Faster, More Frequent Deployments

Buddy has been built to make DevOps easier for everyone – including developers, designers and quality assurance teams. Taking just minutes to set up, it can significantly speed up the build, testing and deployment processes. Best of all, this can all be achieved within a highly-visual UI.

You can automate pretty much anything related to web development. Tasks such as SSH commands, generating static websites, site monitoring, along with building and pushing changes are just a few examples.

In addition to Laravel, Buddy also works with several popular tools and platforms. Staples such as React, WordPress, Shopify, MySQL, Google Cloud, Docker, AWS, Kubernetes and a whole lot more – over 100 in total.

A person viewing code on a computer screen.

Start Using Buddy for Free

Buddy is aptly named, as automation is every developer’s best friend. It takes the pain out of monotonous tasks so that you can focus on more important things.

Sign up for free to start building apps more efficiently and effectively.


This post has been sponsored by Syndicate Ads.

The post Automating Laravel Tests with Buddy <span class="sponsored_text">Sponsored</span> appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/automating-laravel-tests-with-buddy/feed/ 0
20 PHP Snippets for Making the WordPress Admin Easier for Clients https://speckyboy.com/20-snippets-and-hacks-to-make-wordpress-user-friendly-for-your-clients/ https://speckyboy.com/20-snippets-and-hacks-to-make-wordpress-user-friendly-for-your-clients/#respond Thu, 27 Jun 2019 22:28:19 +0000 http://speckyboy.com/?p=12812 These PHP code snippets will allow you to control areas of the WordPress Dashboard, and customize it to benefit your client's tech level.

The post 20 PHP Snippets for Making the WordPress Admin Easier for Clients appeared first on Speckyboy Design Magazine.

]]>
Out-of-the-box, WordPress is an easy-to-use CMS. But for your non-tech-savvy clients, it could be a nightmare, and a potential disaster for the site you have just built.

By simplifying the system and adding some quick hacks to disable or hide certain areas, you can not only help clients, you will also give yourself peace of mind by knowing that the site is safe by removing any potential disaster.

The PHP code snippets below will allow you to control almost all aspects of the WordPress Dashboard, and customize it to benefit your client’s level of tech comfort.

There are, of course, many plugins that will achieve the same function as these snippets, but with code, you get added control and security and, in most cases, will not need to be updated.

You might also like these useful .htaccess snippets, or these WordPress SQL Snippets.

Disabling WordPress Plugin Deactivation

This snippet is particularly useful if you have given a client plugin activation/deactivation privileges (allowing them to add new plugins themselves), but the site you have built requires some core plugins to function and should never be deactivated.

The code below will remove the ‘Deactivate’ links from whichever plugins you deem fundamental, as well as removing the ‘Edit’ links from all plugins.

Paste this into your functions.php:

add_filter( 'plugin_action_links', 'slt_lock_plugins', 10, 4 );
function slt_lock_plugins( $actions, $plugin_file, $plugin_data, $context ) {
  // Remove the edit link for all
  if ( array_key_exists( 'edit', $actions ) )
    unset( $actions['edit'] );
  // Remove deactivate link for crucial plugins
  if ( array_key_exists( 'deactivate', $actions ) && in_array( $plugin_file, array(
    'slt-custom-fields/slt-custom-fields.php',
    'slt-file-select/slt-file-select.php',
    'slt-simple-events/slt-simple-events.php',
    'slt-widgets/slt-widgets.php'
  )))
    unset( $actions['deactivate'] );
  return $actions;
}

Disabling WordPress Theme Changing

Just like the Plugin Disabling code above, you really don’t want your clients tinkering or experimenting with any theme changes. The code below will remove the ‘Appearance’ menu option from the Dashboard.

Paste this snippet into your functions.php:

add_action( 'admin_init', 'slt_lock_theme' );
function slt_lock_theme() {
  global $submenu, $userdata;
  get_currentuserinfo();
  if ( $userdata->ID != 1 ) {
    unset( $submenu['themes.php'][5] );
    unset( $submenu['themes.php'][15] );
  }
}

Disable Top-Level Menus from the WordPress Admin Panel

Depending on your client, you may need to take disabling/hiding WordPress menu options even further. With this snippet, you can hide whichever Top-Level Menu (Posts, Media, Links, Tools…) you need to.

Paste this into your functions.php:

function remove_menus () {
global $menu;
  $restricted = array(__('Dashboard'), __('Posts'), __('Media'), __('Links'), __('Pages'), __('Appearance'), __('Tools'), __('Users'), __('Settings'), __('Comments'), __('Plugins'));
  end ($menu);
  while (prev($menu)){
    $value = explode(' ',$menu[key($menu)][0]);
    if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
  }
}
add_action('admin_menu', 'remove_menus');

Disable Submenus from the WordPress Admin Panel

Maybe your client doesn’t need the drastic action taken by the above snippets, and only needs some key sub-menu items disabled/hidden. This code will help.

Paste this into your functions.php:

function remove_submenus() {
  global $submenu;
    unset($submenu['index.php'][10]); // Removes 'Updates'.
    unset($submenu['themes.php'][5]); // Removes 'Themes'.  
    unset($submenu['options-general.php'][15]); // Removes 'Writing'.
    unset($submenu['options-general.php'][25]); // Removes 'Discussion'.       
}
add_action('admin_menu', 'remove_submenus');

The menu-ID:s are found in wp-admin/menu.php.

Restrict WordPress Admin Menu Items Based on Username

Say you want to restrict client access to certain Top-Level menu items, but you still want to maintain the full menu for the main administrator. This snippet will help.

Replace ‘clients-username’ and paste this code into your functions.php:

function remove_menus()
{
    global $menu;
    global $current_user;
    get_currentuserinfo();

    if($current_user->user_login == 'clients-username')
    {
        $restricted = array(__('Posts'),
                            __('Media'),
                            __('Links'),
                            __('Pages'),
                            __('Comments'),
                            __('Appearance'),
                            __('Plugins'),
                            __('Users'),
                            __('Tools'),
                            __('Settings')
        );
        end ($menu);
        while (prev($menu)){
            $value = explode(' ',$menu[key($menu)][0]);
            if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
        }// end while

    }// end if
}
add_action('admin_menu', 'remove_menus');

Remove WordPress Meta-Boxes from Posts & Pages Editor Screens

Publishing posts and pages are more than likely key to your client’s business and probably the main reason you chose WordPress for them in the first place. To help avoid any confusion from within the posts/pages editor screens, it could be helpful to remove unused meta-boxes (custom fields, recent comments, post tags…).

Paste this into your functions.php and edit as required:

function remove_extra_meta_boxes() {
remove_meta_box( 'postcustom' , 'post' , 'normal' ); // custom fields for posts
remove_meta_box( 'postcustom' , 'page' , 'normal' ); // custom fields for pages
remove_meta_box( 'postexcerpt' , 'post' , 'normal' ); // post excerpts
remove_meta_box( 'postexcerpt' , 'page' , 'normal' ); // page excerpts
remove_meta_box( 'commentsdiv' , 'post' , 'normal' ); // recent comments for posts
remove_meta_box( 'commentsdiv' , 'page' , 'normal' ); // recent comments for pages
remove_meta_box( 'tagsdiv-post_tag' , 'post' , 'side' ); // post tags
remove_meta_box( 'tagsdiv-post_tag' , 'page' , 'side' ); // page tags
remove_meta_box( 'trackbacksdiv' , 'post' , 'normal' ); // post trackbacks
remove_meta_box( 'trackbacksdiv' , 'page' , 'normal' ); // page trackbacks
remove_meta_box( 'commentstatusdiv' , 'post' , 'normal' ); // allow comments for posts
remove_meta_box( 'commentstatusdiv' , 'page' , 'normal' ); // allow comments for pages
remove_meta_box('slugdiv','post','normal'); // post slug
remove_meta_box('slugdiv','page','normal'); // page slug
remove_meta_box('pageparentdiv','page','side'); // Page Parent
}
add_action( 'admin_menu' , 'remove_extra_meta_boxes' );

Remove WordPress Pages Columns

Adding this code allows you to remove whichever column from the ‘Pages’ page you feel is not necessary to your client.

Edit as required and paste this snippet into your functions.php:

function remove_pages_columns($defaults) {
  unset($defaults['comments']); 
  return $defaults;    
} 
add_filter('manage_pages_columns', 'remove_pages_columns');

Remove WordPress Posts Columns

Similar to the snippet above, this code will remove columns from the posts page.

Edit as required and paste this code into your functions.php:

function remove_post_columns($defaults) {
  unset($defaults['comments']);
  return $defaults;    
} 
add_filter('manage_posts_columns', 'remove_post_columns');

Removing Default Widgets from the WordPress Dashboard

The majority of the default Dashboard widgets may not be necessary to your non-tech client and could potentially be a disastrous distraction. This snippet will remove whichever widget you define from the Dashboard.

Paste this into your functions.php:

// Create the function to use in the action hook
function example_remove_dashboard_widgets() {
  // Globalize the metaboxes array. This holds all the widgets for wp-admin
 
  global $wp_meta_boxes;
 
  // Remove the incoming links widget
  unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']); 
 
  // Remove right now
  unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
  unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
  unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
}
 
// Hoook into the 'wp_dashboard_setup' action to register our function
add_action('wp_dashboard_setup', 'example_remove_dashboard_widgets' );

To view each widget’s call, have a look at the Dashboard Widgets API page on the Codex.

Create Personalized WordPress Dashboard Widgets

When building themes for clients, it could be useful and appreciated to create a personalized ‘Welcome’ widget on the Dashboard. This snippet will create a simple ‘Hello World’ widget and can be easily edited to your own specifications.

Paste this code into your functions.php:

// Create the function to output the contents of our Dashboard Widget
function example_dashboard_widget_function() {
  // Display whatever it is you want to show
  echo "Hello World, I'm a great Dashboard Widget";
} 
 
// Create the function use in the action hook
function example_add_dashboard_widgets() {
  wp_add_dashboard_widget('example_dashboard_widget', 'Example Dashboard Widget', 'example_dashboard_widget_function');
}
// Hoook into the 'wp_dashboard_setup' action to register our other functions
add_action('wp_dashboard_setup', 'example_add_dashboard_widgets' );

Add, Remove & Reorder Dashboard Widgets By Role

You may have a client that needs the WordPress Dashboard customized depending on user roles by restricting editors or authors to all of the admins details. This code will get rid of the ‘Incoming Links’ widget for authors and editors and then clean up some of the other boxes for everyone.

Paste this into your functions.php:

function tidy_dashboard()
{
  global $wp_meta_boxes, $current_user;
 
  // remove incoming links info for authors or editors
  if(in_array('author', $current_user->roles) || in_array('editor', $current_user->roles))
  {
    unset($wp_meta_boxes['dashboard']['normal ']['core']['dashboard_incoming_links']);
  }
   
  // remove the plugins info and news feeds for everyone
  unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);
  unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
  unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
 
}
//add our function to the dashboard setup hook
add_action('wp_dashboard_setup', 'tidy_dashboard');

Here’s a list of how to unset each of the current default dashboard widgets:

//Right Now - Comments, Posts, Pages at a glance
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
//Recent Comments
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);
//Incoming Links
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);
//Plugins - Popular, New and Recently updated WordPress Plugins
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);

//WordPress Development Blog Feed
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
//Other WordPress News Feed
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
//Quick Press Form
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);
//Recent Drafts List
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_recent_drafts']);

Remove Author Metabox/Options & Move to Publish MetaBox

This code will remove the Author MetaBox and Screen Options and then add those options into the publish metabox.

Paste this into your functions.php:

// MOVE THE AUTHOR METABOX INTO THE PUBLISH METABOX
add_action( 'admin_menu', 'remove_author_metabox' );
add_action( 'post_submitbox_misc_actions', 'move_author_to_publish_metabox' );
function remove_author_metabox() {
    remove_meta_box( 'authordiv', 'post', 'normal' );
}
function move_author_to_publish_metabox() {
    global $post_ID;
    $post = get_post( $post_ID );
    echo '<div id="author" class="misc-pub-section" style="border-top-style:solid; border-top-width:1px; border-top-color:#EEEEEE; border-bottom-width:0px;">Author: ';
    post_author_meta_box( $post );
    echo '</div>';
}

Add or Remove Links From the WordPress Admin Bar

The WordPress Admin Bar gives you quick access to all of the main areas of your site, like creating a new post or page, moderating comments, or modifying widgets. The snippets below will allow you to add or remove any links.

This snippet will add links to the admin bar. Paste into your functions.php:

function my_admin_bar_link() {
  global $wp_admin_bar;
  if ( !is_super_admin() || !is_admin_bar_showing() )
    return;
  $wp_admin_bar->add_menu( array(
  'id' => 'diww',
  'parent' => 'my-blogs',
  'title' => __( 'Title of the link you want to add'),
  'href' => admin_url( 'https://mysitesurl.com/wp-admin.php' )
  ) );
}
add_action('admin_bar_menu', 'my_admin_bar_link');

This snippet will remove links from the admin bar. Paste into your functions.php:

function remove_admin_bar_links() {
  global $wp_admin_bar;
  $wp_admin_bar->remove_menu('my-blogs');
  $wp_admin_bar->remove_menu('my-account-with-avatar');
}
add_action( 'wp_before_admin_bar_render', 'remove_admin_bar_links' );

Show an Urgent Message in the WordPress Admin

This snippet will allow you to show a custom message to any logged-in user. Particularly useful if you need to inform a client/user that they have done something wrong.
Firstly, paste this into your functions.php:

/**
 * Generic function to show a message to the user using WP's
 * standard CSS classes to make use of the already-defined
 * message color scheme.
 *
 * @param $message The message you want to tell the user.
 * @param $errormsg If true, the message is an error, so use
 * The red message style. If false, the message is a status
  * message, so use the yellow information message style.
 */
function showMessage($message, $errormsg = false)
{
  if ($errormsg) {
    echo '<div id="message" class="error">';
  }
  else {
    echo '<div id="message" class="updated fade">';
  }

  echo "<p><strong>$message</strong></p></div>";
}    

Next, add a hook to the admin notices function to show your custom message:

/**
 * Just show our message (with possible checking if we only want
 * to show the message to certain users.
 */
function showAdminMessages()
{
    // Shows as an error message. You could add a link to the right page if you wanted.
    showMessage("You need to upgrade your database as soon as possible...", true);

    // Only show to admins
    if (user_can('manage_options') {
       showMessage("Hello admins!");
    }
}

/**
  * Call showAdminMessages() when showing other admin
  * messages. The message only gets shown in the admin
  * area, but not on the frontend of your WordPress site.
  */
add_action('admin_notices', 'showAdminMessages');

Hide the WordPress Upgrade Message

You may have clients who do not want to deal with any maintenance updates. For those clients using this snippet, you can hide the WordPress Upgrade Message.

Paste this into your functions.php:

add_action('admin_menu','wphidenag');
function wphidenag() {
remove_action( 'admin_notices', 'update_nag', 3 );
}

Simpler WordPress Login URL

The default URL for logging into your WordPress-powered site is: https://yoursite.com/wp-login.php. To make things easier, or at least more memorable, for a client, you will need a cleaner URL like: https://yoursite.com/login

Paste this code in your .htaccess file before the default WordPress rewrite stuff:

RewriteRule ^login$ https://yoursite.com/wp-login.php [NC,L]

Change the Dashboard Footer Text

When building a site for a client, it can be useful to be able to customize the dashboard footer text. This little snippet will do the job.

Edit “Your own text” and paste this into your functions.php:

function remove_footer_admin () {
    echo "Your own text";
} 

add_filter('admin_footer_text', 'remove_footer_admin');

Changing the WordPress Login Logo

When building themes for clients, one of their expectations may be to have some sort of company branding within WPs admin. The first page a client will ever view is the login screen, and it’s very easy to customize by simply replacing the default WordPress logo with your client’s company logo.

The new logo should be 326×82 pixels, and copy it to your themes ‘images’ folder.

Edit ‘companylogo.png’ and paste this code into your functions.php:

// login page logo
function custom_login_logo() {
  echo '<style type="text/css">h1 a { background: url('.get_bloginfo('template_directory').'/companylogo.png) 50% 50% no-repeat !important; }</style>';
}
add_action('login_head', 'custom_login_logo');

Adding a Custom WordPress Dashboard Logo

The next step in customizing WPs backend is to replace the Dashboards logo. You will need to create a transparent (.gif or .png) image of 30x31px. Then, save that image in your theme’s image folder (/wp-content/themes/theme-name/images) and name it whatever you like.

Edit ‘custom-logo.gif’ and paste this snippet into your functions.php:

//hook the administrative header output
add_action('admin_head', 'my_custom_logo');

function my_custom_logo() {
echo '
<style type="text/css">
#header-logo { background-image: url('.get_bloginfo('template_directory').'/images/custom-logo.gif) !important; }
</style>
';
}

.

The post 20 PHP Snippets for Making the WordPress Admin Easier for Clients appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/20-snippets-and-hacks-to-make-wordpress-user-friendly-for-your-clients/feed/ 0
How to Test Your WordPress Website for PHP 7.x Compatibility https://speckyboy.com/test-wordpress-website-php-7-compatibility/ https://speckyboy.com/test-wordpress-website-php-7-compatibility/#respond Sun, 27 Jan 2019 21:02:22 +0000 https://speckyboy.com/?p=105219 There are a number of benefits to running your WordPress website on a recent version of PHP. Among the most noticeable perks is the massive increase in speed. PHP 7.3...

The post How to Test Your WordPress Website for PHP 7.x Compatibility appeared first on Speckyboy Design Magazine.

]]>
There are a number of benefits to running your WordPress website on a recent version of PHP. Among the most noticeable perks is the massive increase in speed. PHP 7.3 runs about three times as many requests per second when compared with PHP 5.6.

While performance is important, there is something even more concerning. Both PHP 5.6 and 7.0 reached their end-of-life at the end of 2018. That means neither version is receiving crucial security fixes. Therefore, the longer you remain on one of these non-supported versions, the more potential there is for something bad to happen.

Also of note is that WordPress is currently recommending that your web server run PHP 7.3 and is making plans to drop support for anything lower than PHP 5.6. But in this case, running at the bare minimum isn’t good enough.

So, if you’re utilizing an outdated version of PHP, it’s time to get up-to-speed. But before you upgrade, it’s important to test your site to ensure that it will continue running smoothly afterwards.

Let’s have a look at some considerations and testing methods you can leverage to get your site ready for PHP 7.x.

Considerations and Potential Roadblocks

It stands to reason that, the older your site is, the more potentially problematic running on the latest versions of PHP will be. The code that makes up the themes and plugins we use evolves over time. As such, you’ll find that some methods that were acceptable a few years ago have since become either deprecated or removed altogether.

So, before you test anything related to a PHP upgrade, it’s important that your WordPress install is fully up-to-date. That means WordPress core, along with your theme and plugins are running at their latest versions.

But what if a theme or plugin hasn’t had a new version released in a few years? That could pose a problem when upgrading your version of PHP. If these items have unsupported code, they may display errors or stop your site from even loading (the dreaded White Screen of Death).

Testing, which we’ll get to in a moment, will give you a better picture of trouble spots. But it’s worth keeping in mind that some parts of your site may need fixed or replaced.

The other major consideration is your web host’s setup. Which PHP versions do they offer? Are you able to easily switch versions in case you run into problems? Do they have plans to abandon versions 5.6 and/or 7.0? Knowing the answers to these questions will help you create the best possible plan of attack.

PHP Code in a WordPress theme.

Testing Methods

Whether your site is large or small, it’s important to perform some tests before you attempt to use a newer version of PHP. It requires some extra effort, but could save you from some frustrating downtime.

How you test will depend on the resources you have available and, more generally, your working knowledge of PHP. Here, we’ll focus on a couple of more basic ways to test.

Use a Staging Server
Ideally, you’ll have access to a staging environment that is running the exact version of PHP you’ll be upgrading to. This will provide you with an accurate result and a view of what’s working (and what’s not).

But even if your web host can’t provide this for you, it’s still possible to put together a local server that can approximate the experience. Software such as Bitnami, WAMP and XAMPP can get you up and running fairly quickly.

Either way, having access to a cloned version of your site makes the testing process much easier. With debugging turned on, you can thoroughly check the front and back ends for any show-stopping issues.

Run a Compatibility Check
While not always 100% accurate, you can also use a compatibility checking tool to see how your WordPress install holds up on a specific version of PHP.

The free PHP Compatibility Checker plugin will search through your site’s theme and plugin code in an attempt to uncover some common issues. You can select the major version of PHP you want to test against (7.1 or 7.2, for example) and the plugin will do the rest. An itemized report is generated that will show any potential problems that have been found.

Report generated by PHP Compatibility Checker.

Finding and Fixing Errors

If your site is displaying errors, you’ll need to invest some time in finding their source and then repairing them. Sometimes, the errors themselves will lead you right to the culprit. For example, one that mentions the path of a specific plugin would be a pretty good indicator of where you should look for solutions. But it’s not always that easy.

If the error is a bit more vague, you’ll need to put on your detective’s hat and do some troubleshooting. The standard procedure in WordPress is to deactivate all plugins and switch to a default theme, such as Twenty Nineteen. This is another reason why you’ll want to use a staging environment if at all possible.

With all of your plugins deactivated and the default theme in place, load up the site on the front end. Notice any errors? Odds are that they will have been eliminated, since you’re running a completely stock install of WordPress.

Next, it’s time to start activating plugins and testing them, one-by-one. Turn on a plugin, and click around on the front end. No errors? Repeat the process until you’ve found the troublemaker. If none of your plugins are triggering an error, then move on to your theme.

Once you know which item(s) are problematic, you can look for solutions. In the case of a third-party plugin or theme, you’ll want to start with the support forums and see if you can find others who have had the same issue. Perhaps there’s a solution. Or, you can at least report the problem to the author.

If that doesn’t lead to a fix, some decisions have to be made. Software that has known compatibility issues that aren’t being fixed means that you’ll probably have to move on to something else. Hopefully, you can find a suitable alternative that you can test and implement.

Note that, while you can theoretically patch third-party software on your own, it’s a temporary band-aid at best. A future update could overwrite your work and lead to a broken site.

If the offending code is something you’ve written, dig through the PHP documentation and see how you can bring it up-to-standard. While it may be tedious, this is still better than having to rely on someone else to fix their product.

PHP Documentation

Better Speed and Security

After you’ve cleaned up any issues on your site and are running PHP 7.x, you can sit back and enjoy the benefits. Your site will process requests much faster, thus improving the user experience.

Even better is that you’ll have some piece of mind in knowing that, whenever any security holes are found in PHP, they’ll be patched. Then there is the satisfaction of knowing that your WordPress website is running on code that is compatible with the latest standards.

Upgrading PHP isn’t necessarily the must enjoyable or fun experience. In fact, it can be quite frustrating when trying to track down and fix errors. But the end result makes it truly worth the effort.

The post How to Test Your WordPress Website for PHP 7.x Compatibility appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/test-wordpress-website-php-7-compatibility/feed/ 0
phpMyAdmin Turns 15 Years Old This Week! https://speckyboy.com/phpmyadmin-turns-15-years-old-week/ https://speckyboy.com/phpmyadmin-turns-15-years-old-week/#respond Thu, 12 Sep 2013 07:21:22 +0000 http://speckyboy.com/?p=43775 In an era when everything on the internet is shrinking in terms of life expectancy, be it smartphone operating systems or browser versions, phpMyAdmin, the extremely popular and often taken...

The post phpMyAdmin Turns 15 Years Old This Week! appeared first on Speckyboy Design Magazine.

]]>
In an era when everything on the internet is shrinking in terms of life expectancy, be it smartphone operating systems or browser versions, phpMyAdmin, the extremely popular and often taken for granted tool for administering MySQL and other related databases from a web browser, this week has turned 15 years of old!

phpMyAdmin started as a humble project with modest aspirations. Inspired by Peter Kuppelwieser’s MySQL-Webadmin, Tobias Ratschiller began work on phpMyAdmin in 1998, but later abandoned the already popular project in 2000 due to lack of time. It was eventually Olivier Müller, Marc Delisle and Loïc Chapeaux that in 2001 eventually registered phpMyAdmin at SourceForge, and development has never looked back.

phpMyAdmin Turns 15 Years Old This Week!

Today, with over 200,000 direct downloads per month, it has evolved into a gigantic concept in its own right — the number of lines of code has risen from 13,496 to 508,761, made possible by over 650 contributors from across the globe, translated into 72 languages, and the total cost of it all coming in at the relatively cheap total of $7,485,316.

Happy Birthday phpMyAdmin. All the best for the next 15!

The post phpMyAdmin Turns 15 Years Old This Week! appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/phpmyadmin-turns-15-years-old-week/feed/ 0
Website Speed Part 4 : PHP Programming for Speed https://speckyboy.com/website-speed-part-4-php-programming-for-speed/ https://speckyboy.com/website-speed-part-4-php-programming-for-speed/#comments Mon, 12 Mar 2012 09:00:34 +0000 http://speckyboy.com/?p=20300 Programming for speed is not what most coders think of. What they tend to consider first, and usually only, is getting it working. Sometimes people will talk of refactoring to...

The post Website Speed Part 4 : PHP Programming for Speed appeared first on Speckyboy Design Magazine.

]]>
Programming for speed is not what most coders think of. What they tend to consider first, and usually only, is getting it working. Sometimes people will talk of refactoring to reduce the amount of code, but again this is usually only for those that suffer with the luxury of having too much money and time.

I wish I had that luxury, to be able to spend twice as long on a problem to make a perfect solution. In truth I don’t most of the time, as I am out there getting new clients, making other products or not in the fortunate position to have a client with very deep pockets.

To counteract these things I have a bunch of methods stored in my head that allow me to choose the best path first time (I hope!). I am going to share these best practices with you so you can maybe do the same, maybe even better. If you have any great speed suggestions for coding, please comment and I will append it to this post.

Also, please note that this is not an exhaustive list. This is more of a pointer to things you should consider in your favorite coding language. Although this is for PHP specifically, I’ve tried to keep it as generic as possible to make it possible for all coders, no matter the language, to benefit.

Making IF ELSE smaller

IF is possibly the most used statement from all the programming languages, and I think the most used by a noob programmer (hey I was one once, I remember my code).

Common IF ELSE usage


  if ( $something == true ){
  $value = 'yes';
  }else{
  $value = 'no';
  }

Now using only IF


  $value = 'no';
  if ( $something == true ){
  $value = 'yes';
  }

As you can see all that has been done is that value is pre-set to ‘no’ and only gets changed to ‘yes’ if something is true. Both bits of code have the same outcome, one has less code.

If you only have 1 command inside the if statement then you can take things a little further. PHP does not require that you have the curly brackets when there is just one line.


  $value = 'no';
  if ( $something == true )
  $value = 'yes';

Ternary operators

We can go a stage further and have Ternary Operators. These are mathematical instructions that allow for a yes/no answer, just like IF.

IF presented as ternary operation


  $value = ( $something == true ) ? &quot;yes&quot; : &quot;no&quot; ;

Again the same IF ELSE statement, made much smaller. What it does is check the if the statement inside the brackets is either true or false, if it is true it will set value to be “yes”, if it is false it will set value to be “no”

syntax of ternary operators


  output = ( true/false condition ) ? true-value : false-value ;

It is not essential to have an output, as the true or false value could call a function and not return a value.

Using Range to create an array of numbers

Often people will code an array with just a bunch of numbers in it so that they can loop through it.

PHP code to create a select drop down list


  // selected item value
  $item = 12;
  // create array of numbers
  $array_of_numbers = array( 2,4,6,8,10,12,14,16 );
  // start the select 
  echo &quot;&lt;select name='myselect' &gt;&quot;;
  foreach ($array_of_numbers as $number){
  // use terany operator to compare $number and $item, if the same make $selected = &quot;selected&quot;
  $selected = ( $number == $item ) ? &quot;selected&quot; : &quot;&quot; ;
  // echo option, with details filled in
  echo &quot;&lt;option value='&quot; . $number . &quot;' &quot; . $selected . &quot; &gt;&quot; . $number . &quot;&lt;/option&gt;&quot;;
  }
  echo &quot;&lt;/select&gt;&quot;;

Now the same thing shorter with range


  // selected item value
  $item = 12;
  // start the select
  echo &quot;&lt;select name='myselect' &gt;&quot;;
  foreach ( range(2,16,2) as $number){
  // use ternary operator to compare $number and $item, if the same make $selected = &quot;selected&quot;
  $selected = ( $number == $item ) ? &quot;selected&quot; : &quot;&quot; ;
  // echo option, with details filled in
  echo &quot;&lt;option value='&quot; . $number . &quot;' &quot; . $selected . &quot; &gt;&quot; . $number . &quot;&lt;/option&gt;&quot;;
  }
  echo &quot;&lt;/select&gt;&quot;;

Range is a really handy thing, as what it does is created an array of numbers (integers). It has the following syntax in php:


  range($start_number, $end_number, $increment);

The only needed compulsory items are the start and end number, the increment defaults to 1, but can be any number you like.

A range function is available in most languages but is unfortunately not available in Javascript out of the box, so to make this same saving in code you would be best to use a FOR loop

FOR loop version


  // selected item value
  $item = 12;
  // start the select
  echo &quot;&lt;select name='myselect' &gt;&quot;;
  for($number = 2; $number &lt;= 16; $number = $number + 2){
  // use ternary operator to compare $number and $item, if the same make $selected = &quot;selected&quot;
  $selected = ( $number == $item ) ? &quot;selected&quot; : &quot;&quot; ;
  // echo option, with
  echo &quot;&lt;option value='&quot; . $number . &quot;' &quot; . $selected . &quot; &gt;&quot; . $number . &quot;&lt;/option&gt;&quot;;
  }
  echo &quot;&lt;/select&gt;&quot;;

Turbo charging the FOR loop

Many people like to use a for loop as they believe that it is faster than a foreach. While this is often true, it does not offer the flexibility of foreach and with the wrong programming techniques can be slower

The slower FOR loop


// some text as a string
$text=&quot;We love SpeckyBoy&quot;;
// loop through all the characters
for($i=0; $i &lt; strlen($text); $i++){
// look for the o in the text string at the position of $i using a ternary operator
// echo true or false value as needed
echo ( substr($text,$i,1) == 'o' ) ? &quot;its an o&quot; : &quot;no o here&quot;;
}

The faster FOR loop


// some text as a string
$text=&quot;We love SpeckyBoy&quot;;
// get the length of the string
$length = strlen($text);
// loop through all the characters
for($i=0; $i &lt; $length ; $i++){
// look for the o in the text string at the position of $i using a ternary operator
// echo true or false value as needed
echo ( substr($text,$i,1) == 'o' ) ? &quot;its an o&quot; : &quot;no o here&quot;;
}

The 2nd for loop is faster as it does not need to re-check the string length each time the loop runs. The first loop will check the string length 17 times with the text used

Making your code easier to maintain, and faster

I often see the same problem with my noob code when I re-visit it. The code is all written on 1 line and very long. Check this bit of code as an example:


  $html = &quot;&lt;input name='&quot; . $name . &quot;' id='&quot; . $id . &quot;' value='&quot; . $value . &quot;' class='&quot; . $theclass . &quot;' type='checkbox' &quot; . $checked . &quot; /&gt;&quot;;
  echo $html;

It works just fine, and will be ok for any implementation, but there are some problems with it. For example if the class is empty, it is wasteful to code the empty class setting. While this may not make so much difference to a Javascript implementation, as this is being generated on the server with PHP, you’d be sending extra bytes to the clients browser which are not required. This of course will make the most difference when making AJAX calls and waiting for the reply, where extra bytes can make much more of an impact.

An easier way to maintain


  $attributes = &quot; name='&quot; . $name  . &quot;' &quot;;
  $attributes .= &quot; id='&quot; . $id  . &quot;' &quot;;
  $attributes .= &quot; value='&quot; . $value  . &quot;' &quot;;
  $attributes .= ($theclass != '' )?  &quot; class='&quot; . $theclass  . &quot;' &quot; : &quot;&quot; ;
  $attributes .= ($selected == $value )?  &quot; checked &quot; : &quot;&quot; ;
  $html = &quot;&lt;input type='checkbox' &quot; . $attributes  . &quot; /&gt;&quot;;
  echo $html;

As you can see, much easier to read, much easier to maintain, and used on the server side will produce less HTML code.

Don’t echo every line only the final output

It’s much easier to echo every line, or pass control back to HTML, than it is to write every line to a variable, yet writing the output to a variable first and only echoing at the end is the faster way to process

The easy way to do things, with a few variations


echo &quot;&lt;h2&gt;&quot; . $title . &quot;&lt;/h2&gt;&quot;; ?&gt;
&lt;small&gt;&lt;?php echo date(); ?&gt;&lt;small&gt;

The more server friendly way to do things

$output = &quot;&lt;h2&gt;&quot; . $title . &quot;&lt;/h2&gt;&quot;;
$output .= &quot;&lt;small&gt;&quot; . date() . &quot;&lt;small&gt;&quot;;
echo $output;

OK, this is a very simplistic example of what you should do as it is only 2 lines and then output.

Rounding up

This is a very short list of things to help make your PHP coding faster and easier to maintain. There is of course many more things that you can do to reduce the amount of code that you do use, or the speed that it runs at.

Most of these techniques can be taken across to other programming languages, so when your coding in Javascript or .NET give it some thought and you will be making things much faster.

More from the Website Speed series…

Website Speed Part 1: Write More Efficient CSS →
Website Speed Part 2: Working With and Optimizing Images for the Web →
Website Speed Part 3 – Caching WordPress →

The post Website Speed Part 4 : PHP Programming for Speed appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/website-speed-part-4-php-programming-for-speed/feed/ 22