You are currently viewing PHP for WordPress

PHP for WordPress

  • Post author:
  • Post category:General
  • Post comments:0 Comments
  • Post last modified:April 7, 2024
  • Reading time:9 mins read

Table of Contents

PHP Coding Conventions

  • All PHP files must end in .php
  • Statements (or commands) in PHP end with a semicolon (;)
  • If you want to include comments, which are nonfunctional notes, you can do so in two way
				
					// Single-line comments are two forward slashes.
/* Multiline, or block comments, start with a forward slash and an asterisk. They end
with an asterisk and forward slash. */
				
			

Variables

A way to store information in order to reference it later

Defining a Variable

It should start with a dollar sign $ following an alphanumeric name.

  • For variable names with more than one word, it’s a good practice to us underscores between the words
				
					<?php
    $age = 34;
?>
				
			

Variable Types

We do not need to declare what kind of data our variable are most of the time. This makes PHP a weak typed language.

  • Integers: Whole numbers (for example, 0, 45, or 128)
  • Floats: Numbers with decimal points (for example, 1.0 or 3.16)
  • Characters: Single letters, numbers, or symbols
  • Strings: Collections of characters (for example, ‘Hello’ or ‘Racer 5’
  • Booleans: True or False

Some points:

  • 1 vs. “1”: Numbers with and without quotes are
    handled differently. You can do calculations with 1, but not ‘1’.
  • ‘A’ vs. ‘a’: Uppercase and
    lowercase letters are represented differently in PHP.
  • Arrays: Arrays are another variable type you’ll
    learn all about later.

Strings in PHP

Double Quotes: Strings in double quotes will be processed by PHP before they’re outputted.

				
					<?php
    $age = 43;
    echo "Hoomaan is $age years old"; // Double quote with the variable inside
				
			
				
					<?php
    $age = 43;
    echo 'Hoomaan is ' . $age . ' years old'; // Single quote with period before and after the variable.
				
			
				
					<?php
    echo "Hoomaan's real name in high school was \"Hamidreza\""; // Using escape character before the double quotes inside another double quotes.
    
    /* Escape Characters
    \n for a new line
    \\ for a backslash
    \$ for a dollar sign
    \t for a tab
    */
    
    // Escape characters only work inside a double quotes string. The only escape character that works inside a single quote string is back slash single quote: \'
				
			

Arrays

				
					<?php

$colors = array( 'red', 'green', 'blue', 'yellow' );
print_r( $colors );
echo $colors[1]; // green
    
/* Output of print_r:

Array
(
    [0] => red
    [1] => green
    [2] => blue
    [3] => yellow
)

*/
				
			
				
					<?php

$hoomaan = array(
    'name' => 'Hoomaan',
    'age' => 43,
    'job' => 'Front-end developer',
);
echo $hoomaan['job']; // Front-end developer
				
			

Arithmetic Operators and Math in PHP

  1. Addition with +
  2. Subtraction with –
  3. Multiplication with *
  4. Division with /
  5. Get the remainder with %

PEMDAS

  1. Parentheses
  2. Exponents
  3. Multiplication and division
  4. Addition and subtraction
				
					<?php

echo 5 * 6 + 3 - 1 . "\n"; // Output will be 32
echo 5 * (6 + 3) - 1 . "\n"; // Output will be 44
echo 3**2 . "\n" ; // Output will be 9 - Exponent
echo 5**2 * ( 6 + 3 ) - 1 . "\n"; // Output will be 224
				
			

Comparison Operators

Allow us to compare values and evaluate them as true or false.

				
					<?php

// Equality operator: ==
// Only compares the VALUE
10 == 10 // True
10 == 20 // False
'1' == 1 // Would evaluate to True

// Identical Comparison: ===
// Compares the VALUE and the TYPE
1 === 1 // True
'1' == 1 // False

// Greater than comparison: >
// Less than comparison: <

// Not or Negation: !
// Not equal: !=
// Not Identical: !==
				
			

Logical Operators

				
					<?php

/* &&: Both sides should be true in order to get the TRUE output
(true && true is true)
(true && false is false)
(false && false is false)
*/

/* ||: Only one side is enough to be true in order to get the TRUE output
(true || true is true)
(true || false is true)
(false || false is false)
*/
				
			

Control Structures

  • A single if always goes first
  • The first condition to evaluate as true will be the one that runs. The rest will be ignored
  • The else statement always goes last—it serves as a catchall if none of the conditions are true
				
					<!-- Alternative Syntax:
if ( condition to check) :
    // code to execute if the condition is true
elseif ( different condition) :
    // different code to execute
else:
    // catchall code
endif;
-->

<?php if ($home_page ) : ?>
<header> <h1>Welcome to the home page of my website!</h1>
<p>Have a look around.</p>
</header>
<?php endif; ?>
				
			

Yoda Conditionals

It’s recommended to use Yoda conditionals when you’re going to check the equality of a variable.

Put the variable at the right side of the conditions. This will prevent accidental assignment and bugs in your code.

				
					<!--Good-->
<?php if ( 10 == $1 ) { /* do somentiong */ } ?>

<!--Bad-->
<?php if ( $1 == 10 ) { /* do somentiong */ } ?>
				
			

Loops

While loops vs Foreach loops

While loops: “Do something while the condition is true”

  • General-purpose loops used for math, enumeration, or anything you can think of

Foreach loops: “Do something for each item in a list”

  • Used to process arrays
				
					// While Loop

while ( condition is true ) {
    /*Code to execute. Should include to eventually make condition false */
}
				
			
				
					// Foreach Loop

$items = array ('1', '2', '3');
foreach ( $items as $item ) {
    // Do something with next item in the array
}

$colors = array( 'best' => 'red', 'better' => 'blue', 'good' => 'green', 'ok' => 'yellow' );

foreach ( $colors as $rank => $color ) {
    echo "$color is $rank \n";
}
				
			

Functions

Reusable snippets of code that can be called multiple times

				
					function hello_world () {
    return "Hello World";
}

echo '<p>'. hello_world() . '</p>';
				
			
				
					<!--Function Printing-->
<?php
function hello_world () {
    echo "Hello World";
}
?>

<p><?php hello_world(); ?></p>
				
			
				
					// Passing Arguments
function is_bigger($a, $b) {
    return $a >= $b;
}
$bigger = is_bigger (10, 5);
				
			

WordPress Functions file

Class

A code definition or template for creating objects

Object

A group of variables and functions marked by a single identifier.

Hooks

Allow us to insert our own code into WordPress without modifying “core”

There are two types of hooks:

  • Actions: Changes how WordPress does something (imagine adding air conditioning to your house)
  • Filters: Modifies the information WordPress retrieves (image painting your house

Leave a Reply