Lesson 38 of 50
76% Complete
76%

Introduction to PHP in WordPress

PHP is a server-side programming language used extensively by WordPress. It helps generate webpage content, process requests, retrieve database information and implement dynamic website functionality.

Learning Objective: Understand PHP basics, learn how PHP works in WordPress, explore variables, conditions, loops and functions, and understand how WordPress template files use PHP.

1. What Is PHP?

PHP stands for PHP: Hypertext Preprocessor. It is a server-side scripting language that can generate HTML dynamically. WordPress uses PHP to build pages and implement many of its core features.

Example: Simple PHP Code
<?php
echo "Hello, World!";
?>

Output: Hello, World!

Save this example as a PHP file and run it using a PHP server, such as a local XAMPP installation.

2. How PHP Works in WordPress

When a visitor requests a WordPress page, the web server runs the necessary PHP code. WordPress loads the relevant data and template logic, then sends the generated response to the browser.

Basic Request Flow
  1. A visitor opens a WordPress page.
  2. The web server processes the PHP request.
  3. WordPress loads the required files and data.
  4. PHP generates the page's HTML output.
  5. The browser displays the resulting webpage.

The browser receives the generated response, not the server's PHP source code.

3. Where Is PHP Used in WordPress?

WordPress Core
WordPress core uses PHP for many operations, including loading the application, processing requests and managing content.
Theme Development
Theme PHP files can generate page layouts, display content and use template functions.
Plugin Development
Plugins use PHP to add features such as custom content types, forms, settings and integrations.
Database Operations
WordPress uses PHP to work with stored content, settings and other information through its database APIs.

4. PHP Opening and Closing Tags

PHP code is commonly written between <?php and ?> tags. A PHP file can contain both PHP code and HTML markup.

Example: PHP with HTML
<!DOCTYPE html>
<html>
<body>

<h1>
    <?php echo "Welcome to WordPress"; ?>
</h1>

</body>
</html>

PHP generates the heading text, and the browser displays it inside the HTML heading.

5. PHP Variables

Variables store values that a PHP program can use. In PHP, variable names begin with a dollar sign ($).

Example: PHP Variables
<?php
$institute = "Soopro Pathshala";
$course = "Web Development";
$duration = 6;

echo $institute;
echo "<br>";
echo $course;
echo "<br>";
echo $duration;
?>

Output:

Soopro Pathshala
Web Development
6

6. PHP Data Types

PHP supports different data types for storing and working with information.

Data Type Example Purpose
String "Hello" Stores text.
Integer 100 Stores whole numbers.
Float 99.50 Stores decimal numbers.
Boolean true Represents true or false.
Array ["HTML", "CSS"] Stores multiple values.
Null null Represents the absence of a value.

7. PHP Conditions

Conditional statements allow PHP to make decisions based on whether a condition is true or false.

Example: If-Else Statement
<?php
$fee = 5000;

if ($fee >= 5000) {
    echo "Course fee is eligible for this offer.";
} else {
    echo "Course fee is below the offer amount.";
}
?>

Output: Course fee is eligible for this offer.

8. PHP Loops

Loops repeat a block of code. They are useful when displaying multiple values, such as a list of courses.

Example: Foreach Loop
<?php
$courses = ["HTML", "CSS", "JavaScript", "PHP"];

foreach ($courses as $course) {
    echo $course . "<br>";
}
?>

Output:

HTML
CSS
JavaScript
PHP

9. PHP Functions

A function is a reusable block of code. PHP functions help organize code and avoid unnecessary repetition.

Example: Create a Function
<?php
function welcomeStudent($name) {
    return "Welcome, " . $name;
}

echo welcomeStudent("Rahul");
?>

Output: Welcome, Rahul

10. What Is functions.php?

A theme's functions.php file is used to register theme features and add theme-specific functionality. It is loaded as part of the active theme.

Example: Register a Theme Feature
<?php

function soopro_theme_setup() {
    add_theme_support('title-tag');
}

add_action('after_setup_theme', 'soopro_theme_setup');

This example enables WordPress to manage the document title for the theme.

Important: Use a child theme when adding theme-specific code to a classic theme, or use a suitable custom plugin for functionality that should remain active when the theme changes. Back up your site and test code before deploying it.

11. WordPress Template Tags

WordPress provides template functions that themes can use to display information dynamically.

Function Purpose
bloginfo('name') Displays the site title.
the_title() Displays the current post or page title in the loop.
the_content() Displays the current post or page content in the loop.
the_permalink() Displays the permalink for the current post in the loop.
get_header() Loads the theme header template.
get_footer() Loads the theme footer template.

12. Example: Display WordPress Posts

WordPress themes can use the Loop to retrieve and display posts. The following is a simplified example for a classic theme.

WordPress Loop
<?php
if (have_posts()) {
    while (have_posts()) {
        the_post();
        ?>

        <h2>
            <a href="<?php the_permalink(); ?>">
                <?php the_title(); ?>
            </a>
        </h2>

        <div>
            <?php the_content(); ?>
        </div>

        <?php
    }
} else {
    echo 'No posts found.';
}
?>

This code is intended for a suitable classic theme template. Block themes often use HTML templates and blocks instead of writing the Loop directly in a template file.

13. PHP Security in WordPress

PHP code can access data and perform actions on the server. WordPress developers must validate input, check permissions and escape output appropriately.

Important Security Practices
  • Validate and sanitize incoming data as appropriate.
  • Escape output using the correct WordPress escaping functions.
  • Use capability checks before privileged operations.
  • Use nonces to help protect relevant form submissions and actions.
  • Use WordPress database APIs and prepared queries where appropriate.
  • Never expose passwords, API secrets or database credentials.
  • Test code on a staging site before using it in production.

14. Practical Assignment

Activity: Practice PHP for WordPress

Complete these tasks in a local PHP environment or test WordPress site:

  1. Create a PHP file that prints "Welcome to WordPress".
  2. Create variables for institute name, course name and fee.
  3. Use an if-else statement to check a course fee.
  4. Create an array containing five course names.
  5. Use a foreach loop to display all course names.
  6. Write a function that accepts a student name and returns a welcome message.
  7. Locate the active theme's functions.php file without modifying core files.
  8. Identify three WordPress template functions and explain their purpose.
  9. Explain why PHP source code should not be exposed to website visitors.
Practice theme code in a child theme or test environment. A PHP syntax error in an active theme or plugin can interrupt the website.

Lesson Summary

  • PHP is a server-side programming language used by WordPress.
  • PHP generates dynamic HTML for the browser.
  • Variables, conditions, loops and functions are basic PHP concepts.
  • The theme's functions.php file registers theme-specific functionality.
  • Template tags help display WordPress content.
  • The WordPress Loop is used in classic templates to display queried posts.
  • Secure PHP development requires validation, escaping and permission checks.

Lesson 38 Quiz

Choose the correct answer for each question.

Q1. What is the main role of PHP in WordPress?
Q2. Which file is commonly used to add theme-specific PHP functionality?
Q3. What does the WordPress function the_title() do in the Loop?