Start a Project

Enhancing Developer Productivity: Using AI in WordPress theme development

Tony - a web support agent with Wibble web design northern ireland
By Tony Irvine 11 September, 202310 MIN READ
Using AI in WordPress theme development by Wibble Web Design and Web Development

TL;DR: In the rapidly evolving landscape of technology, AI continues to redefine how we approach stunning web designs and creative web development, but it has been a huge time-saver for me as part of an award winning team. I’ve found it valuable for pushing my development skills by verifying my code, suggesting alternatives and ensuring my code remains accessibility-friendly up to September 2021. There’s more to explore on this topic later in the article.

Web development and AI

From my perspective, AI has rapidly grown in size and significance in recent months. It’s being integrated into various domains, including images, games and possibly even our everyday appliances soon. The possibilities that AI offers have both amazed and worried me as an artist and, to some extent, as a developer. It seems to have the potential to render art almost redundant. This sense of concern prompted me to delve into how AI’s advancements could impact my work.

So, here are my pros and cons of AI when used correctly, (I have not always done this):

ProsCons
Efficiency: AI-powered tools can automate repetitive tasks, speeding up development and reducing manual labour.Dependency Risk: Relying heavily on AI may lead to a lack of in-depth understanding of code and concepts.
Code Optimization: AI can analyze your code and suggest optimizations, leading to cleaner, more efficient code.False Positives: AI’s error detection might flag non-issues, potentially wasting time on unnecessary corrections.
Error Detection: AI can identify potential errors, bugs, or vulnerabilities in your code, helping prevent issues down the line.Privacy Concerns: AI tools might process sensitive data, raising privacy and security concerns.
Enhanced Productivity: By automating routine tasks, you can focus on more creative and complex aspects of development.Limited Creativity: AI can assist with repetitive tasks but lacks human creativity and innovation.
Learning Acceleration: AI-driven platforms offer quick answers to coding queries, accelerating your learning process.Complexity: Some AI-powered tools require a learning curve, diverting attention from actual development.
Innovation: AI can introduce you to new coding paradigms, techniques, and libraries that you might not have encountered otherwise.Inaccuracy: AI-generated code might not align perfectly with project needs, requiring manual adjustments.
Custom Solutions: AI can help tailor solutions to specific project requirements, resulting in more precise and effective outcomes.Lack of Context: AI might misunderstand nuanced queries, leading to incorrect or irrelevant responses.
Accessibility and Inclusivity: AI tools can assist in making your codebase more accessible and user-friendly for diverse audiences.Maintenance Challenges: Integrating AI tools into your workflow might require ongoing updates and maintenance.
Real-time Assistance: AI chatbots or tools provide instant guidance, enabling faster issue resolution and development progress.Dependency on Data: AI’s accuracy relies on the quality and relevance of the training data it uses.
Data Analysis: AI can help you interpret large datasets, enabling data-driven decision-making during development.Dehumanisation: Over-reliance on AI might reduce the human touch and unique insights in your development process.

My initial foray into AI in the context of my work occurred when I realised that my Googling skills weren’t always up to par. I noticed my colleagues being incredibly patient with my inquiries, so I decided to leverage a new platform where artificial intelligence could address countless questions. This approach was intended to save my colleagues time and maintain their sanity. I began by posing simple queries that I already had some knowledge about. This ensured I was on the right track toward my desired outcome. From there, I gradually delved deeper into the code and its ultimate function.

I have spent some time exploring Chat Open AI and experimenting with code snippets for various tasks, such as loop queries, button styling and asset animations. I tested these snippets and observed how AI responded to my inquiries. I learned to rephrase my questions to obtain the most accurate answers. Once I identified effective strategies, I worked on enhancing the efficiency of my workday. However, I aimed to achieve this without becoming overly reliant on AI-generated code. My intention was to augment my development knowledge and understand the rationale behind established practices.

Using AI with WordPress development

The next significant development for me was the integration of an AI plugin into PHP Storm’s integrated development environment (IDE). This enabled me to centralise my queries in one place. Thus, I embarked on building my first small WordPress theme. My focus was on adding new scrolling galleries using swiper.js and WP blocks. Let’s outline the plan:

  • Develop a swiper block.
  • Perform all setup tasks within the WordPress admin interface.
  • Create the necessary block components to handle the swiper/gallery functionality.
  • Implement a standardised code block and predefined variables for basic setup.
  • My subsequent tasks would involve adapting the solution to each new theme’s style, incorporating essential Advanced Custom Fields (ACF), and linking to the relevant block for usage.

An example of my initial query might be:

Leveraging the power of WordPress along with the latest advancements in Swiper.js, I aim to establish an automated method for incorporating a repeater (*img1) field into my Theme Options. This setup will be restricted to Site Admins and will include several fields that Swiper requires to function as a gallery. The necessary fields within my repeater will include:

(List the required fields, e.g., Swiper Name – Text Field, Swiper Loop – True/False Field, Swiper Lazy Load – True/False Field, etc.)

Advanced Custom Fields | Swiper Setup

*img1 – image only for reference, as I will not use this in my query

After adding a new swiper to the repeater within my theme options and saving the changes, I need to create a new block folder/file.

Here’s what I have set up:

  • Block: I have created a block-swiper-default (including files, names, and settings) and defined the path to the block.
  • Swiper JavaScript File: I have set up the swiper.js file (including naming and path).

In my swiper.js, I need to create a loop that retrieves information from the repeater if it’s not empty and integrates it into my swiper code.

I recently posed this scenario to Chat Open AI (https://chat.openai.com/) to obtain a set of steps for setting this up correctly. It responded with:

“Certainly! It appears you want to establish a WordPress theme configuration that enables the management and display of Swiper.js galleries using Advanced Custom Fields (ACF) repeater fields, while restricting options to Site Admins. Here’s a detailed guide on how to achieve this:

Step 1: Prepare your Theme

  1. **Set up the ACF Repeater Field using the latest version of Advanced Custom Fields**:
    • In your WordPress admin panel, go to “Custom Fields” and create a new field group for your Swiper options.
    • Add a repeater field named “Swiper Options” to this group.
    • Inside the repeater, add the required fields: Swiper Name (Text), Swiper Loop (True/False), Swiper Lazy Load (True/False), Slides per view (Number), Mobile Slides Per View (Number), Tablet Slides Per View (Number), Laptop Slides Per View (Number), and Desktop Slides Per View (Number).
  2. **Lock the ACF Field Group**:
    • Use a plugin like “ACF Lockdown” to lock down the ACF field group so only Site Admins can access and modify it.
  3. **Create the block**:
    • Duplicate your `block-default` folder and rename it to something like `block-swiper`.
    • Inside the `block-swiper` folder, rename `render.php` to something relevant, e.g., `render-swiper.php`.
    • Adjust the content of `block.json` to match the Swiper block’s requirements.
  4.  **Create Swiper JavaScript File**:
    • Create `_swiper.js` in your theme’s `src/js/` folder.

Step 2: Modify Your Swiper JavaScript File

(function ($) {
    var swiper_loaded = false;

    function checkSwiperExists($class) {
        return $($class).length === 0;
    }

    function swiper($class, options) {
        if (checkSwiperExists($class)) return false;
        swiper_loaded = true;
        return new Swiper($class, options);
    }

    // Wait for the document to be ready
    $(document).ready(function () {
        // Loop through each Swiper option row from ACF repeater
        $('.swiper-options').each(function () {
            var $row = $(this);
            var swiperOptions = {
                slidesPerView: $row.find('.slides-per-view').text(),
                loop: $row.find('.swiper-loop').text() === '1',
                lazy: $row.find('.swiper-lazy-load').text() === '1',
                // Add more options using the same approach
            };
            swiper(".swiper-logos", swiperOptions);
        });
    });

})(jQuery);

Step 3: Modify Your Theme Files

a. **Edit Your Theme’s `functions.php`**:

  • Enqueue the ACF CSS and JS files as well as your Swiper JavaScript.
  • Load your Swiper block’s stylesheet and JavaScript.
  • Enqueue your modified Swiper JavaScript file.
<?php
function enqueue_theme_assets() {
    // Enqueue ACF CSS and JS files here
    // Enqueue Swiper CSS and JS files here
    wp_enqueue_script('swiper-js-custom', get_template_directory_uri() . '/src/js/_swiper.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_theme_assets');
?>

b. **Render Swiper block in Template**:

  • In your template file where you want the Swiper to appear, use a WordPress loop to fetch the repeater field data and generate the HTML for each Swiper.
<?php
// Query the repeater field rows
$swiper_options = get_field('swiper_options');
if ($swiper_options) {
    foreach ($swiper_options as $swiper_option) {
        // Extract field values
        $slides_per_view = $swiper_option['slides_per_view'];
        $swiper_loop = $swiper_option['swiper_loop'];
        $swiper_lazy_load = $swiper_option['swiper_lazy_load'];

        // Output HTML for Swiper
        echo '<div class="swiper-options">';
        echo '<div class="slides-per-view">' . esc_html($slides_per_view) . '</div>';
        echo '<div class="swiper-loop">' . esc_html($swiper_loop) . '</div>';
        echo '<div class="swiper-lazy-load">' . esc_html($swiper_lazy_load) . '</div>';
        // Output more fields...
        echo '</div>';
    }
}
?>

Step 4: Display Swiper on the Frontend

  • Make sure your template is displaying the HTML structure properly.
  • When you load the page, the Swiper block should be initialised and display the galleries based on the ACF repeater field data.

Remember to adjust the class names and field names as necessary based on your actual ACF field setup and HTML structure. This guide provides a general outline of the steps you need to follow to achieve your goal. You may need to customise and adapt the code to your specific theme structure and requirements.

From this point, I’ll proceed to build out my files and code, returning to address any potential issues that may arise. I’ll enable debug logs in my development environment to identify and troubleshoot any problems. If all goes as planned, I may not need to ask many questions. However, if complications arise, I can refer back to this chat for solutions or further debugging steps.

PHP Storm also has a number of AI options for any code you select in the IDE itself as seen here:

AI Assistant | A Php Storm plugin as standard

In conclusion

AI serves as an excellent tool for expanding my web development capabilities by encouraging me to explore new concepts. As a kinetic learner, it accelerates my learning process through hands-on experience. Prior to using AI, I often engaged in copying and pasting code snippets from platforms like StackExchange or juggling multiple tabs in search of solutions. AI provides a centralised location for answers and promotes a deeper understanding of the rationale behind the code.

I’ve established a workflow that empowers me to investigate queries and challenges independently, reducing the need for initial Team Wibble consultations. The finalised solution can then be presented to my colleagues for collaborative evaluation, code review, security assessments, accessibility enhancements, and project impact analysis. This approach streamlines communication, mitigates unnecessary internet distractions, and optimises time management.

I encourage everyone to explore AI’s potential and benefits. If it doesn’t align with your preferences, you can continue with your existing coding methodologies. I’m curious to hear your thoughts on AI’s future in development.

Here at Wibble, we specialise in web design and web development. Get in touch today and let us transform your web projects into captivating digital experiences, to start your creative journey towards something beautiful.


Share this blog post

Tony - a web support agent with Wibble web design northern ireland

Tony Irvine

More from author