INF 270: WordPress — Week 9: PHP Logic for WordPress
Announcement
No in-person class next Thursday (3/26)!
Keep up with your work on Blackboard (readings and discussion board posts)
Recap: Why PHP Matters in WordPress
Last week we covered PHP syntax and variables. This week we focus on three core skills used constantly in WordPress themes and plugins: functions, conditionals, and loops.
- Functions let you reuse logic
if/elsecontrols what content users see- Loops output repeating content like posts and menus
Test your code at https://php-play.dev/
1. Functions in PHP
A function is a reusable block of code. It can accept input (parameters) and optionally send a value back with return.
<?php
function format_price($amount) {
return "$" . number_format($amount, 2);
}
$price = format_price(19.99);
echo $price; // $19.99
Note the example above uses
number_format(), a built-in PHP function. You can see the instructions here. In WordPress, functions are often connected to hooks. Use add_action() to run your function at a specific point in the page lifecycle, and use add_filter() to modify a value before WordPress outputs it.
<?php
function student_modify_title($title) {
return "⭐ Featured: " . $title;
}
add_filter('the_title', 'student_modify_title');
Note that this code won't work outside of a WordPress environment. add_filter() and add_action() are specific to WordPress.
The above code can also be written more simply using an anonymous function (closure):
<?php
add_filter('the_title', function ($title) {
return "⭐ Featured: " . $title;
});
2. Conditional Logic with if/else
Conditionals allow your page to respond to different situations, such as user login state, post type, category, or custom field values.
<?php
$score = 78;
if ($score >= 90) {
echo "A";
} elseif ($score >= 80) {
echo "B";
} elseif ($score >= 70) {
echo "C";
} else {
echo "Needs more work";
}
WordPress has many helper functions designed for conditionals, such as is_user_logged_in(), is_front_page(), and is_single().
<?php if (is_user_logged_in()) : ?>
<p>Welcome back! Here are your account links.</p>
<?php else : ?>
<p>Please <a href="/my-account">log in</a> to continue.</p>
<?php endif; ?>
endif;. <?php
// Option 1: Curly brackets
if (is_user_logged_in()) {
echo "Welcome back!";
} else {
echo "Please log in.";
}
// Option 2: Alternative syntax
if (is_user_logged_in()) :
echo "Welcome back!";
else :
echo "Please log in.";
endif;
Using switch() for multiple exact matches
Use switch() when one variable can match several known options. It is often cleaner than a long chain of if / elseif checks.
<?php
$template = "archive";
switch ($template) {
case "front-page":
echo "Load homepage hero and featured sections.";
break;
case "single":
echo "Load full post layout with author box.";
break;
case "archive":
echo "Load post grid and pagination.";
break;
default:
echo "Load default fallback layout.";
}
3. Loops in PHP
Use loops when you want to repeat output without writing the same markup over and over.
for loop
In a for() loop, you define a starting point, an ending point, and an increment.
<?php
//this will print out 5 times
//$i starts at 1, and as long as it's less than or equal to 5,
//it will run the code inside the loop, then increase $i by 1 each time
for ($i = 1; $i <= 5; $i++) {
echo "Lesson " . $i . "<br />";
}
foreach loop
When working with arrays, a foreach() loop is easier to write and read. It moves through each item in the array and makes it available as a variable.
<?php
$categories = ["News", "Tutorials", "Announcements"];
foreach ($categories as $category) {
echo "<li>" . $category . "</li>";
}
while loop
A while() loop keeps running as long as a condition is true. You must update a value inside the loop, or it can run forever.
<?php
$draft_count = 3;
while ($draft_count > 0) {
echo "You still have " . $draft_count . " draft posts.<br />";
$draft_count--;
}
echo "All drafts are published!";
The WordPress Loop
The most important loop in WordPress is the post loop. It checks whether posts exist, then moves through each post and prints content.
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<article>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p><?php the_excerpt(); ?></p>
</article>
<?php endwhile; ?>
<?php else : ?>
<p>No posts found.</p>
<?php endif; ?>
When you work on index.php, archive.php, or single.php templates, this pattern appears constantly.
Lab #5
Head over to Blackboard and start working on Lab #5. You will be creating a custom plugin that uses these concepts to display a dynamic message to customers depending on the value of the items in their cart.