fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← WordPress

WordPress / 9 MIN READ

WP Template Child Theme PHP

Creating a child theme with PHP

From the original Fervor library. Examples may use older package versions.

🌟 PHP Arrays: Pro Tips & Cool Stuff 🌟

You’re ready to take your PHP array skills to the next level! Here are pro tips, cool tricks, and mind-blowing facts that will make you an array wizard. 🧙‍♂️


🛠️ Pro Tips for PHP Arrays

1️⃣ Short Syntax Saves the Day

Instead of using the old array() syntax, always use [] for arrays. It’s cleaner and modern!

$fruits = ["apple", "banana", "cherry"];

Why It’s Cool: Saves time typing and makes your code look more modern. Plus, it’s supported in PHP 5.4+.


2️⃣ Combine Two Arrays with Keys and Values

Use array_combine() to merge one array as keys and another as values.

$keys = ["name", "age", "email"];
$values = ["Alice", 25, "alice@example.com"];
$user = array_combine($keys, $values);
print_r($user);

Why It’s Cool: Turns two simple arrays into a powerful associative array. 🧩


3️⃣ Destructure Arrays (PHP 7.1+)

Grab array values directly into variables using list-like syntax.

$colors = ["red", "green", "blue"];
[$first, $second, $third] = $colors;
echo $first; // Outputs: red

Why It’s Cool: Makes working with arrays feel like unwrapping a present. 🎁


4️⃣ Merge Arrays Smartly

Use the spread operator (...) for clean and modern array merging (PHP 7.4+).

$array1 = [1, 2, 3];
$array2 = [4, 5];
$merged = [...$array1, ...$array2];
print_r($merged);

Why It’s Cool: No more messy array_merge() calls—just sprinkle some ....


5️⃣ Add Default Values to Associative Arrays

Use the null coalescing operator (??) to handle missing keys gracefully.

$user = ["name" => "John"];
$age = $user["age"] ?? 18; // Default to 18 if "age" is not set
echo $age; // Outputs: 18

Why It’s Cool: Prevents errors while keeping your code clean and safe.


6️⃣ Filter Arrays Without Loops

Use array_filter() to keep only the elements you need.

$numbers = [1, 2, 3, 4, 5];
$even = array_filter($numbers, fn($num) => $num % 2 === 0);
print_r($even); // Outputs: [2, 4]

Why It’s Cool: It’s like having a personal assistant that picks the right items for you.


7️⃣ Sort Arrays Like a Pro

PHP offers multiple ways to sort arrays based on your needs.

Sort by Values:

$fruits = ["banana", "apple", "cherry"];
sort($fruits); // Ascending order

Sort by Keys:

$user = ["name" => "Alice", "age" => 30];
ksort($user); // Sorts by keys

Custom Sort:

Use usort() for advanced sorting logic.

$numbers = [3, 2, 5, 1, 4];
usort($numbers, fn($a, $b) => $b - $a); // Descending
print_r($numbers);

Why It’s Cool: From simple to complex, PHP sorting is a lifesaver.


🧩 Cool Tricks for PHP Arrays

1️⃣ Check for Multiple Keys at Once

Verify if all required keys exist in an associative array.

$user = ["name" => "Alice", "email" => "alice@example.com"];
$requiredKeys = ["name", "email"];
$hasAllKeys = !array_diff_key(array_flip($requiredKeys), $user);
echo $hasAllKeys ? "Valid!" : "Missing keys!";

Why It’s Cool: Saves you from writing repetitive isset() checks.


2️⃣ Flatten a Multidimensional Array

Use array_merge() and the spread operator to squash an array into a flat one.

$nested = [[1, 2], [3, 4], [5]];
$flat = array_merge(...$nested);
print_r($flat); // Outputs: [1, 2, 3, 4, 5]

Why It’s Cool: Clean and elegant flattening without loops.


3️⃣ Find Unique Values

Remove duplicates using array_unique().

$numbers = [1, 2, 2, 3, 3, 3];
$unique = array_unique($numbers);
print_r($unique); // Outputs: [1, 2, 3]

Why It’s Cool: Say goodbye to duplicates in one line. 🙌


4️⃣ Shuffle Arrays

Randomize the order of array elements using shuffle().

$cards = ["Ace", "King", "Queen", "Jack"];
shuffle($cards);
print_r($cards);

Why It’s Cool: Perfect for building card games or randomizing stuff.


5️⃣ Map Arrays for Transformation

Use array_map() to apply a function to each element.

$numbers = [1, 2, 3];
$squared = array_map(fn($num) => $num * $num, $numbers);
print_r($squared); // Outputs: [1, 4, 9]

Why It’s Cool: It’s like a factory for modifying arrays.


6️⃣ Reduce Arrays to a Single Value

Use array_reduce() to combine all elements into one value.

$numbers = [1, 2, 3, 4];
$sum = array_reduce($numbers, fn($carry, $num) => $carry + $num, 0);
echo $sum; // Outputs: 10

Why It’s Cool: Turns arrays into meaningful data in seconds.


7️⃣ Get a Random Element

Pick a random value with array_rand().

$fruits = ["apple", "banana", "cherry"];
$randomIndex = array_rand($fruits);
echo $fruits[$randomIndex];

Why It’s Cool: Great for quizzes or lucky draws! 🍀


8️⃣ Turn Arrays Into Strings and Back

Convert arrays to strings and vice versa with implode() and explode().

$fruits = ["apple", "banana", "cherry"];
$commaSeparated = implode(", ", $fruits);
echo $commaSeparated; // Outputs: apple, banana, cherry

$backToArray = explode(", ", $commaSeparated);
print_r($backToArray);

Why It’s Cool: Handy for CSVs or URLs.


Bonus: Reverse Arrays in One Line

$numbers = [1, 2, 3];
$reversed = array_reverse($numbers);
print_r($reversed); // Outputs: [3, 2, 1]

Why It’s Cool: Instant reverse gear! 🚗


🎉 Final Takeaways

PHP arrays are not just tools—they’re Swiss Army knives 🛠️ of programming. With these pro tips and tricks, you can manipulate arrays efficiently and creatively.

Here’s what you should remember:

  • Keep It Clean: Use modern syntax like [] and the spread operator.
  • Think Functional: Use array_map, array_filter, and array_reduce for magic.
  • Be Lazy Smart: Let PHP do the heavy lifting with built-in functions.

Ready to create some epic code?🚀

Bonus Cool Stuff

🌟 Cool Things & Pro Tips for Custom WordPress Page Templates 🌟

Now that you’ve mastered the basics of creating custom page templates in a child theme, let’s jazz things up! Here are some cool ideas and pro tips to take your custom templates to the next level. 🚀


🧩 Cool Things You Can Do with Custom Page Templates

1️⃣ Dynamic Hero Section

Add a fully customizable hero section with a background image and overlay text.

<div class="hero-section" style="background-image: url('<?php echo get_the_post_thumbnail_url(); ?>');">
    <h1><?php the_title(); ?></h1>
    <p><?php echo get_post_meta(get_the_ID(), 'subtitle', true); ?></p>
</div>

What’s Cool:

  • Use the featured image as the background.
  • Add a custom field (subtitle) for the hero tagline using Advanced Custom Fields (ACF) or the default WordPress custom fields.

2️⃣ Custom Query for Specific Content

Pull in posts, products, or portfolios dynamically.

Example: Display Latest Blog Posts

<div class="latest-posts">
    <h2>Latest Posts</h2>
    <?php
    $latest_posts = new WP_Query(['posts_per_page' => 3]);
    if ($latest_posts->have_posts()) :
        while ($latest_posts->have_posts()) : $latest_posts->the_post();
            echo '<h3><a href="' . get_permalink() . '">' . get_the_title() . '</a></h3>';
            the_excerpt();
        endwhile;
        wp_reset_postdata();
    else :
        echo '<p>No posts found.</p>';
    endif;
    ?>
</div>

What’s Cool:
Showcase specific content like blog posts, WooCommerce products, or testimonials directly on your custom page.


3️⃣ Embed Google Maps

Add a Google Map to your custom template for a contact or location page.

<div class="map-container">
    <iframe
        src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3151!2d144.9631!3d-37.8141!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x0!2z37.8141!4m5!1m3!1d120000!2d144.9631!3d-37.8141"
        width="100%"
        height="400"
        style="border:0;"
        allowfullscreen=""
        loading="lazy">
    </iframe>
</div>

What’s Cool: Perfect for a contact page or “Our Locations” page. Customize the map URL for specific locations.


4️⃣ Custom Fields for Flexible Content

Use Advanced Custom Fields (ACF) to add custom data to your template:

  • Add fields for a subtitle, call-to-action buttons, or client testimonials.
  • Display the fields dynamically:
<div class="custom-section">
    <h2><?php the_field('custom_title'); ?></h2>
    <p><?php the_field('custom_description'); ?></p>
    <a href="<?php the_field('custom_button_url'); ?>" class="btn"><?php the_field('custom_button_text'); ?></a>
</div>

What’s Cool:
Empowers non-technical users to update page content without touching code.


5️⃣ Custom Sidebar for Specific Pages

Add a unique sidebar just for your custom template.

  1. Register a new sidebar in your functions.php:

    function register_custom_sidebar() {
        register_sidebar([
            'name' => 'Custom Page Sidebar',
            'id' => 'custom_sidebar',
            'before_widget' => '<div class="widget">',
            'after_widget' => '</div>',
            'before_title' => '<h3>',
            'after_title' => '</h3>',
        ]);
    }
    add_action('widgets_init', 'register_custom_sidebar');
    
  2. Add it to your template:

    <div class="sidebar">
        <?php dynamic_sidebar('custom_sidebar'); ?>
    </div>
    

What’s Cool: Tailor sidebars for specific needs, like adding contact forms or ads for that page.


Include a special footer file for just this template.

  1. Create footer-custom.php in your child theme.
  2. Add this in your template file:
    <?php get_template_part('footer-custom'); ?>
    

What’s Cool: A unique footer lets you add a copyright notice, call-to-action buttons, or social links just for that page.


7️⃣ Load CSS and JS Just for This Template

Avoid bloating your site by loading assets only for your custom page.

function enqueue_custom_template_assets() {
    if (is_page_template('custom-template.php')) {
        wp_enqueue_style('custom-template-style', get_stylesheet_directory_uri() . '/css/custom-template.css');
        wp_enqueue_script('custom-template-script', get_stylesheet_directory_uri() . '/js/custom-template.js', [], null, true);
    }
}
add_action('wp_enqueue_scripts', 'enqueue_custom_template_assets');

What’s Cool: Keeps your site lightweight while adding specific styles and interactivity for the custom page.


8️⃣ Add Pagination to Custom Queries

If your page pulls multiple posts, include pagination.

$custom_query = new WP_Query(['posts_per_page' => 5, 'paged' => get_query_var('paged')]);
if ($custom_query->have_posts()) :
    while ($custom_query->have_posts()) : $custom_query->the_post();
        the_title('<h3>', '</h3>');
    endwhile;

    // Pagination
    echo paginate_links([
        'total' => $custom_query->max_num_pages
    ]);
endif;
wp_reset_postdata();

What’s Cool: Adds a professional touch by letting users navigate through multiple posts.


💡 Pro Tips for Custom Page Templates

1️⃣ Name Your Templates Clearly

Use meaningful names to avoid confusion when selecting templates in WordPress admin:

/* Template Name: Portfolio Page */

2️⃣ Reuse Sections with get_template_part()

Modularize your code by breaking it into reusable parts.

  • Create a parts folder in your child theme.
  • Add files like hero.php or contact-form.php.
  • Load them dynamically:
    <?php get_template_part('parts/hero'); ?>
    <?php get_template_part('parts/contact-form'); ?>
    

3️⃣ Debug with Conditional Tags

Use conditional tags to check when your template is active.

if (is_page_template('custom-template.php')) {
    echo "Custom template is active!";
}

4️⃣ Optimize with Transients

Cache data for faster loading, especially for custom queries.

$cached_posts = get_transient('latest_posts');
if (!$cached_posts) {
    $cached_posts = new WP_Query(['posts_per_page' => 3]);
    set_transient('latest_posts', $cached_posts, 12 * HOUR_IN_SECONDS);
}

5️⃣ Mobile-Friendly Templates

Ensure your template is responsive by testing on mobile. Add a meta viewport tag to the header:

<meta name="viewport" content="width=device-width, initial-scale=1">

6️⃣ Use SVGs for Icons

Instead of loading multiple icon fonts, use inline SVGs for sharp, lightweight icons.

<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
    <path d="M12 0L15 5H9L12 0Z"></path>
</svg>

7️⃣ Test in Different Browsers

Ensure your template looks consistent across Chrome, Firefox, Safari, and Edge. Tools like BrowserStack or LambdaTest can help.


8️⃣ Backup Before Big Changes

Always make a backup before tinkering with templates, especially on live sites. Tools like UpdraftPlus make it easy.


🎉 Wrap-Up

Custom page templates in WordPress are incredibly powerful. With these cool ideas and pro tips, you can create stunning, functional pages that stand out. Whether you’re designing a portfolio, blog, or unique landing page, the possibilities are endless.

Let me know if you want help with advanced features like animations, custom post types, or integrating APIs! 🚀

Keep your curiosity going.Explore more WordPress →
287 TUTORIALS · 22 TOPICSREADY