Learn the basics of the PHP language and its importance in WordPress development

WordPress uses a group of different languages ​​and basic programming technologies, learning which will help you take a step forward in dealing with WordPress, from simply creating and customizing WordPress sites to becoming a WordPress developer.

The most important of these languages ​​are (HTML, CSS, and JavaScript), which operate on the client side, and PHP, which operates on the server side.

The HTML language is responsible for determining the structure of the site, the CSS language is responsible for coordinating and designing its elements, and the JavaScript language is responsible for adding advanced interactive features such as scroll bars and other interactive features.

As for the PHP language, it is what enables the WordPress site to interact with the database and retrieve data from it in conjunction with a language responsible for querying the site’s database, such as MySQL or MariaDB.

We have explained the basics of using HTML and CSS , and we have also explained the JavaScript language and how to use it in the structure of the WordPress system in previous articles, and in today’s article we will explain the basics of the PHP language, which is considered the basic language for WordPress development.

Note before starting:

It should be noted that this article does not aim to teach you PHP from A to Z, but it aims primarily to help you as a WordPress developer obtain basic knowledge that will help you recognize the basic rules and understand the code used by the WordPress system according to the latest available version of the language (PHP). 8)

What is PHP language?

PHP is an abbreviation for  Hypertext P re_ P rocessor, meaning hypertext preprocessor language. It is an open source programming language used for programming purposes in general, and for the purpose of developing websites in particular.

PHP is a simple, lightweight server-side language that can be embedded in HTML code and other client-side scripting languages.

PHP also supports the concepts of object-oriented programming or OOP , which includes the concepts of classes, objects, inheritance, etc.

What is the meaning of server-side language or client-side language?

As we mentioned previously, PHP is a server-side scripting language,  unlike some other web development languages ​​that are client-side. So what does this mean?

Actually, web programming languages ​​are classified into two types:

  • Client side programming language
  • Server side programming language

When you visit a web page written in a client-side language, such as (HTML, CSS, or JavaScript), the code is sent directly to your browser so that the browser processes the information and outputs it in the form of a web page. Therefore, these languages ​​are considered client-side languages ​​because their processing occurs on the end user’s device. .

When you visit a web page written in PHP – or any other language on the client side – in this case, the PHP code is first processed by the server.

That is, the entire PHP code is executed on the remote web server, then the result of this processing is obtained in the form of HTML code, after which the remote server sends this resulting page to the user’s browser.

The user will receive HTML code representing dynamic pages containing the contents of the site, and these pages will be displayed on the Internet browser of his local device.

How to write and implement PHP code?

In order to run code server-side, you need a development environment that includes a server that can execute the code. This development environment can be either local or remote.

If you already have a web hosting account on a remote server you can run your code on it, or alternatively you can turn your computer into a local server by installing an emulator such as XAMPP.

In this article, we will rely on running the codes locally without relying on a remote server because we will not need to be connected to the Internet to execute the codes. This speeds up the development process and allows us to see the changes immediately in the browser. It also enables us to test the code in more than one browser.

Read more:
What is XAMPP and how to install and use it
Create a WordPress site on the local server (LocalHost) using XAMPP

If you have installed WordPress on a local server, you are ready to execute PHP codes on your computer, and all you will need to write the codes is a text editor to write your code.

You can use any simple text editor, such as Notepad, but a good text editor can speed up the development process, help you write PHP code and debug, and some code editors include support for WordPress.

There are many suitable text editors that you can rely on such as Atom, Sublime Text, VSCode, PhpStorm, and NotePad++ and you can choose the one that suits you best.

In this article, we will use the VSCode editor because it provides several add-ons that make writing code easier and supports auto-completion of basic PHP functions as well as basic WordPress functions, and add-ons for fixing errors such as the PHP Intelephense WordPress Snippet add-ons, WordPress Toolbox, WordPress Development, and many others, which make it easier for you to write development code. WordPress system.

The way PHP code is written is very similar to how HTML code is written. It begins with typing the tag <?php and ends with typing the tag ?>, and in between, your code instructions are written.

<?php
//Write the code here
?>

Each PHP statement ends with a semicolon; But there is no need to place this semicolon in the last line of code, that is, immediately after the line following the closing tag ?>

The file must be saved with the extension .php, and the PHP file, as mentioned, can contain HTML codes with embedded PHP codes.

To write all the PHP code, I will create a folder called ola inside the htdocs folder inside the xampp folder, that is, the path will be as follows: C:\xampp\htdocs\ola, as follows, and create a file inside it called demo.php

The htdocs folder is the root folder and is the location where I will search Xampp for php codes, and the ola folder will be dedicated to collecting all the codes that I will implement in the explanations of this article. Now I will open the entire folder that I created with the VS Code editor, then I will edit the demo.php file and add the following code to it:

<!DOCTYPE html>
<head>
<title> Hello World PHP Page </title>
</head>
<body>
<?php
echo “Hello World!”;
?>
</body>
</html>

This code uses the echo print instruction, which prints the text string passed after it, and here it prints the phrase Hello World! in the page.

In order to see the result of executing the previous code, open the file through the browser (after making sure that the local server is running

Note 1:

If the file contains only PHP code (not embedded in HTML code) it is best to omit the PHP closing tag at the end of the file, as this prevents accidental whitespace or newlines from being added after the PHP closing tag which could cause unwanted effects.

Note 2:

If HTML code is nested with PHP code in one file, any HTML code must be outside the php open and close tags, and any PHP code must be inside these two tags.

What are the basic things a WordPress developer should learn in PHP?

1.Comments

Comments in any programming language are lines of code that are not implemented, and their primary purpose is to explain how the code works to any other users who will use this code. Sometimes comments are used to disable part of the code so that it does not execute.

You can write comments in PHP in several ways as follows:

<?php
// One-line comment
# One-line comment
/*
Component comment
Of several lines
*/
//The following code will not be executed
//echo “Hello World!”;
echo “Wpar.net”;

2.VARIABLES

It is important to know the concept of variables, the way they are defined, and the different types of variables in PHP. A variable in any programming language is used to express a space for storing and dealing with data in memory, and the value that is stored in the variable can change during the execution of the program.
Variables in PHP are declared using the symbol $ followed by the variable name, and then the type of the variable is determined by the type of the value passed to it.

The PHP language supports several types of variables, whether simple variables such as (bool, int, float, string) that store a single value, or complex variables that store several values ​​at the same time such as (array, object, callable, iterable), in addition to variables of a special type. They are (NULL and resource)

Variable names in PHP are case sensitive, that is, $var and $VAR are considered two different variables. The variable name must begin with a letter or an underscore and cannot begin with a number, but it can contain a number after the first letter of the name.
For example, the following code defines the types Different variables in php

$v_bool = TRUE ; //Boolean variable
$v_str = “foo” ; //Text string
$v_str2 = ‘foo’ ; //Text string
$v_int = 12 ; // Integer
// matrix
$v_array = array(
“foo” => “bar”,
“bar” => “foo”,
);

To know the type of any particular variable, PHP provides two functions for this: var_dump() and gettype(), for example:

echo var_dump ( $v_bool ) ; //bool(true) prints
echo gettype ( $v_int ) ; // integer prints

Global and Superglobal Variables

In general, in programming languages, including PHP, variables are limited in scope, that is, you cannot access the variables that you know in the code except in a specific field or scope, and this field is determined according to the foundations and rules of each language.

To make variables global, you must specify this explicitly using the global keyword as follows:

<?ph
global $g_var;
?>

PHP has a set of high-level global variables that are predefined and you can use them directly anywhere in the code without any prior declaration.

For example, session data and cookies are stored in high-level global variables $_COOKIE and $_SESSION to be continuously available throughout the site. Note that the values ​​of the session variable $_SESSION are saved on the server, while the values ​​of the $_COOKIE variable are saved in the browser from Client side.

The WordPress system also provides a set of global variables to store various information. For example, information about the user, such as whether the user has logged in or not, and the type of browser through which the user visits the website, is stored in global variables.
Information about the site’s pages is also stored in global variables. For example, when browsing a specific publication, all the details of the current publication are stored in a global variable $post, and when browsing publications under a specific category, all these publications belonging to this category are stored in a global variable $wp_query, and so on. So you can use it in your code.

alert!

Working with global variable values ​​is important for understanding how WordPress works and developing themes and plugins. Although defining variables to be public is an easy way to share information throughout the website, they must be used with caution because they can be a vulnerability to sabotage your site. Being public means that anyone who uses them directly can change their value.

3.VARIABLES

A constant in a programming language is an identifier used to store a fixed value that cannot change during the execution of the code. Constants in PHP are case sensitive, as are variables, and it is preferable for their names to begin with uppercase letters.

It is not possible to assign a value to a constant directly. Rather, the constant is defined and its value is determined using the define() function, where we pass to this function the name of the constant and its value. The value of the constant can be read directly through its name or through the constant() function.

Most constants are usually used in code to store site settings, for example:

<?php
define(‘LOCATOR’, “/locator”);
define(‘CLASSES’, LOCATOR.“/code/classes”);
define(‘FUNCTIONS’, LOCATOR.“/code/functions”);
define(‘USERDIR’, LOCATOR.“/user”);
define(“MINSIZE”, 50);
echo LOCATOR; // Prints /locator
echo constant ( “LOCATOR” ) ; // Prints the same code as before

4. Conditional Statements

Conditional instructions are used in the PHP language to control the execution of the code, as is the case in many other programming languages. They allow you to use conditions to display content based on certain criteria, and they have several forms, the most important of which are:

  • A simple if statement that tests a single condition and only executes the code when it is true.
  • The if else statement, which tests the condition and its opposite, so that the code is executed when the condition is met and another code is executed if it is not met.
  • The if elseif else statement, which tests a set of conditions so that the code is executed when any of them is met, and the code is executed at the end if any of the above conditions are not met.

Example:

<?php if( date( ‘G’ ) > 18 ) : ?>
< h2 > Good night < /h2 >
<?php else : ?>
< h2 > Happy day < /h2 >
<?php endif ?>

The previous code displays either a good night or a good day message depending on the time the code is executed. It depends on the date(‘G’) function, which returns a number between zero and 23, where zero represents midnight and 23 represents 11 p.m. If the value returned by the function is more than 18, this means that it is after 6 pm, so we display the message saying “Good Night” on the page, otherwise we display the message “Good Day.”

5.Include instruction

This instruction copies the contents of one file to another file, where the path to the required file is placed after the include keyword as follows

include ‘path_to_file’;

It is used on websites in general and on WordPress sites in particular when you want to include the same code in several places in a WordPress template. Through it, you can enter PHP statements into another file – before the server processes them –

This instruction can be very useful for you to avoid duplicating the site’s header, footer, and menu codes instead of writing their codes in multiple files or pages. You can place the header, footer, and menu code in separate files such as header.php, footer.php, and menu.php, and include them on the rest of the pages (other template template files).

You can also upload the code from the functions.php file into the index.php file. You can use the include statement to do this. If the functions.php file includes the following code

<?php
// functions.php
function get_copyright()
{
return ‘Copyright © ‘ . date ( ‘Y’ ) . ‘WordPress in Arabic, all rights reserved’ ;
}
echo get_copyright();

This code can be called inside the file as follows:

<?php
// index.php file
include ‘functions.php’;

If PHP can find the function.php file, the code for the file will be loaded and executed, and the copyright statement will be printed inside the page index.php as follows

If the required file is not found, the code will produce a warning message as follows:

6. Loops

Loops are used to perform repetitive tasks such as navigating through elements of an array of data, or sending e-mail messages to a mailing list, etc. The PHP language includes several forms of repetitive instructions, the most important of which are:

  • While: It is the simplest form of loop, and it repeats the execution of the code contained within it as long as a condition is met (it tests the condition and then executes).
  • do-while: repeats the execution of the code inside it until a condition is no longer met (it executes and then tests the condition).
  • for: The code inside is executed a specified number of times
  • foreach: used exclusively to iterate through the elements of an array (to print its elements or perform certain operations on it…)

For example, WordPress mainly uses loops to display blog posts like this:

<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
//
// Here we display the content of the article
//
} // end while
} // end if

You will notice when browsing the code in WordPress that it uses loops extensively, as they are used within any template file that displays a group of articles, as well as in search pages, archive pages, index files, individual publication pages, and other places..

7. Functions

Functions are blocks of code that perform a set of specific tasks. They are used to encapsulate pieces of code and give them a specific name.

These functions take information in the form of parameters, perform a set of operations on those parameters and return the result of the code.

Programmatic functions are not executed automatically when the page is loaded, but rather they are executed when they are called, that is, at the name of the software function and passing the appropriate parameters to it whenever we need to, so that the function executes its instruction block based on the values ​​of these parameters without the need to repeatedly write the same code.

There are two main types of functions in PHP:

User-defined functions

Custom functions can be defined by the user to accomplish specific tasks according to his requirements. Methods in PHP are defined according to the following form:

<?php
function function_name($arg_1, $arg_2, /* …, */ $arg_n)
{
echo “Example function.\n”;
return $retval;
}
?>

Function names follow the same rules as other naming in PHP and are case insensitive. Since the function name can begin with a letter or an underscore, after which any number of letters, numbers, or underscores can be placed.

You can pass information to functions through a list of parameters that are enclosed in parentheses () after the function name and separated by commas.

As of PHP 8, the list of function parameters can contain a comma at the end after the last parameter name. This comma is ignored, but it is useful if passing a large number of arguments, or if the parameter names are long, so in this case it is preferable to write the parameters as Columnar to make the code more readable.

<?php
function takes_many_args(
$first_arg,
$second_arg,
$a_very_long_argument_name,
$arg_with_default = 5,
$again = ‘a default string’, // This trailing comma was not permitted before 8.0.0.
)
{
// …
}
?>

Built-in functions

They are functions built into the PHP language. PHP contains more than 1,000 built-in functions that can be called directly within the code to perform a specific task. (The WordPress core also adds its own ready-made built-in PHP functions) You can use them to expand and customize your code, and all you have to do is call them and pass the appropriate parameters to them.
But before calling any ready-made function, it is necessary to know how the function works, what it returns, and what values ​​you must pass to it to write correct PHP code.

List of all ready-made functions in PHP

A list of all ready-made functions in the WordPress core

For example, in the previous paragraphs we used several ready-made functions such as the date() function that returns the date and to which we can pass an argument or parameter representing the desired date format. The have_posts() function returns a logical value of True if there are articles and False if there are none.

Other examples of ready-made functions in the WordPress core that are widely used are:

  • get_post_type(): Returns the post type, whether it is a default WordPress post or a custom type
  • get_the_title(): returns the post title
  • the_excerpt() returns the post excerpt
  • the_content() returns the post content
  • the_tags() returns the post tags

There are many other ready-made functions that you can benefit from in WordPress development.
At the following link is a list of the 100 most famous ready-made functions in WordPress

8.The concept of object-oriented programming (OOP)

The PHP language supports an object-oriented programming language (OOP), which is one of the relatively recent programming concepts that is based on the concept of classes or objects ( Objects ), which are sometimes called instances.

In object-oriented programming, rows are created that contain data and programming functions together, so that the row includes a set of properties that are usually private to the row so that they are not modified outside the class code, and a set of software procedures or functions that are usually public so that they are called outside the class code. A class acts as a template or model from which a set of different objects or instances can be created.

Let’s take a real-life example to understand the matter. If we manage to build a house, we first create a plan for the house. The blueprint itself is not a house but an outline of a house. The blueprint can be thought of as a class. When an actual house is built based on this blueprint, the actual house is the object.

Since we can build several identical houses from the same plan, in the same way we can create multiple objects from the same row, but each house can be customized according to our needs. For example, each house may have different paint colors and different interior decorations… In short, the row is a blueprint for creating an object.

 

Now let’s take a programming example that explains the matter. Suppose we want to create a row that represents an article or a blog post. The blog post will have properties such as the article ID, the title, the content itself, the name of the writer, whether it is published or not, the date of publication, etc. It will have its own actions or functions such as publish and edit. And delete the article.

We express this in PHP as follows:

<?php
class Blogpost
{
private $id;
private $title;
private $post;
private $author;
private $is_published;
private $publish_date;
public function publish() {
// Publish the post here
}
public function delete() {
// Delete the post here
}
public function edit() {
// edit the post here
}
}

After we know a row that represents the article, we can rely on it as a model for creating several different articles, as follows:

$first_post = new Blogpost();
$second_post = new Blogpost();

On the other hand, there is an earlier programming concept called procedural programming. The programming code in this type of programming is limited to writing a set of procedures or programming functions that perform operations on data.

Although the WordPress system still relies more on the procedural programming method, and most developers rely on it to develop WordPress templates and plugins, taking advantage of object-oriented programming in development can make the code more usable.

9. Using Namespaces

The names of classes, procedures, and functions must be unique and not repeated on the site so that no conflict occurs between them. However, by using namespaces, the same class or procedure can be used without conflict between them, because each one will work in its own PHP namespace.

For example, in the first file file-A.php within the site, you can name a function called do_something

// file-A.php contains a function under the myCompany\PackageA namespace
namespace myCompany\PackageA;
function do_something() {
// do things
}

In another file file-B.php within the same location, the same name can be used for the do_something() function because we used a different namespace here.

// file-B.php contains a function with the same name
// but under a different namespace
namespace myCompany\PackageB;
functiondo_something(){
// do things
}

It is preferable to rely on namespaces when developing any templates or plugins in WordPress. This makes the code more organized, improves its performance, and makes it less susceptible to conflict errors.

When developing your own WordPress template or plugin, you can use a distinct and unique domain name. For example, you can use a domain name that is the name of your company, your personal name, or the name of the template or plugin that you are developing.

We will be satisfied with this amount of explanation about PHP because the article, as I mentioned at the beginning, is not directed to teach you all the details of the language, but rather it is directed to help you learn the basics that will help you in developing a template or WordPress plugin that is integrated and works correctly.

If you would like to learn more, you will find in the following paragraph a group of important resources that will help you learn the language in detail and in-depth.

Resources to learn more about PHP

Using PHP within WordPress

If you review your WordPress site files, you will be able to see hundreds of programming files and PHP codes, whether within the core folder of the WordPress system , or within the folders for external templates and plugins.

Understanding how these files work will make learning WordPress development much easier. In this paragraph, we will focus more on WordPress template files and try to understand them in more detail, as they are a basic idea about the PHP language that helps us understand what is going on.

In previous articles, we have explained the basic files of WordPress template files and their hierarchy , so it is necessary that you browse these files and understand their working mechanism well in order to be able to manage and develop your site successfully.

For example, let’s explore the default theme files called twentytwentyone that comes implicitly with any WordPress installation.

Since we are working on the local server, we will access the files of this template through the following path: C:\xampp\htdocs\testsite\wp-content\themes, replacing testsite with the name of your sites folder.

Let’s open the content.php file from the default template and take a look at it. This file is responsible for displaying the content of the blog articles in the template (you will find it under the \template-parts\content subdirectory) of the template folder and we try to read the php codes within the file.

If we ignore the php code that includes several lines of comments at the beginning of the file and read the first line after it, it will be the following

<article id=“post-<?php the_ID(); ?>” <?php post_class(); ?>>

We can conclude from reading the previous code that this code uses two ready-made functions in WordPress: the_ID() function , which brings us the ID of the current post, and the post_class() function , which returns the rows of a specific HTML element and is useful for us in designing and formatting this article later.

The following lines of the file include the following PHP code

<?php if ( is_singular() ) : ?>
<?php the_title( ‘<h1 class=”entry-title default-max-width”>’, ‘</h1>’ ); ?>
<?php else : ?>
<?php the_title( sprintf( ‘<h2 class=”entry-title default-max-width”><a href=”%s”>’, esc_url( get_permalink() ) ), ‘</a></h2>’ ); ?>
<?php endif; ?>

Here we have a conditional statement (if-else) that calls the beginning of the ready-made function is_single(), which returns true if we are on a page that displays only one post on the site, otherwise it returns false.
If the condition is met, we will call the the_title function, which displays the title of this post in h1 format. If the condition is not met, we still display the title through the the_title function, but in h2 format, and we also display a link within this title to take us to the page for the individual publication.

Note that the parentheses () after some function names are empty, and the parentheses after others contain multiple values, and this depends on the parameters that the function needs to obtain during its call.

As we mentioned previously, it is necessary to know the parameters of each function by referring to its documentation. For example, the the_title() function , according to the official WordPress documentation, requires three parameters as follows:

the_title( string $before = , string $after = , bool $echo = true )

The first parameter allows us to add HTML before the title, the second parameter allows us to add HTML after the title, and the third parameter is an optional logical parameter that specifies whether we want the function to print the title with an echo statement or just return its value for later use.

The final PHP code contained in this file is the following

<?php twenty_twenty_one_post_thumbnail(); ?>

It is a call to a special function defined within the template and not a ready-made function. If we search for the code to implement this function, we will find it in another file within the template, which is the template-tags.php file located in the inc subfolder. The task of this function, according to its code, is to display the image. The thumbnail or what is known as the featured image of the post.

The deeper you understand the programming details and know the mission of each function and each code in the template, the more you will have the flexibility to use them and adapt them in developing your template.

Learning in this way is fun and encourages you to return to document each function and explore the code, which develops your skills in dealing with it with greater flexibility.
You may not understand everything the first time, but little by little you will come to connect things together and understand everything that goes on behind the scenes of a WordPress template.

There are some other matters and concepts included in the WordPress system that we explained in separate articles that enhance the process of understanding the entire code and we recommend returning to them, such as the concept of hooks in WordPress that allow you to modify the default functions of WordPress, the APIs , the explanation of the WP_Query class in WordPress, and the WordPress loop that Control the display of posts.

And remember that during the learning and development process you may make some errors and this is normal, and in order to be able to discover the cause of the error and for this reason it is necessary to enable the Debug Mode feature that shows any errors in the code to find out the cause of the error and work to solve it, because WordPress cancels… By default this feature is a form of protection.

Read more: Enable Debug Mode in WordPress

Conclusion

Learning the PHP language is essential for anyone who wants to learn WordPress development and gain experience in developing templates and plugins, but you do not have to learn a lot about the PHP language before you start developing WordPress.

It is enough for you to learn the basic principles of the language and try to understand the most important PHP codes used by WordPress, and try to fully understand the codes used in one of the simple templates or plugins, modify them, and understand their working mechanism until the full picture becomes clear to you, and then you can begin developing more advanced templates and plugins.

Once you have a good working knowledge of the source code used in WordPress, you will be able to start doing things yourself and adapting it to suit your requirements. The important thing is that you start and keep in mind that programming requires some effort and commitment from you in learning, skill in research, and patience in solving any problems you encounter during the development journey.

Avatar photo
I am a young man who has been working in WordPress and e-marketing for 10 years. I would like to share my experience with you so that we can become professional in WordPress I will be happy to share the experience with you.