Skip to main content Senior Full Stack Web Developer - Ossi Jalonen

WordPress plugin dev with the help of Claude.ai, part 4

Published: 2024-04-25
Updated: 2024-04-25

Web development, PHP development, WordPress plugin development all have endless elements, features and aspects to choose from, so we won’t go through everything in this series, I don’t want to, or have the knowledge or time to do it. But still, let’s have little short detour here, just to show Claude probably knows all there is to know, as he quickly comes up with new code for whatever I decide would make a good demo for our little post.

As mentioned in all previous posts, it may still be easier to follow along with the full code from this series:
https://github.com/jalonenbrothers/film-review-plugin-demo

Some more WordPress basics

Me:I have a `fetch_and_store_movie_data` method. the movie_data argument includes some film genres. The other movie_data is saved as custom fields with `update_post_meta`, but I'd like to save all given genres as categories of the post. The custom post is film_review, and it has not been set up to include any categories or tags.

To save the movie genres as categories for the film_review custom post type, you can follow these steps:

First, you need to register a new taxonomy for the film_review post type. You can do this by adding the following code in the register_post_types function, inside the $args array:

'taxonomies' => array('genre'), // Register the 'genre' taxonomy

Next, you need to register the genre taxonomy itself. You can do this by adding the following code after the register_post_type function:

function register_taxonomies() {
    $labels = array(
        'name'              => __('Genres', 'jbros-film-review'),
        'singular_name'     => __('Genre', 'jbros-film-review'),
        'search_items'      => __('Search Genres', 'jbros-film-review'),
        'all_items'         => __('All Genres', 'jbros-film-review'),
        'parent_item'       => __('Parent Genre', 'jbros-film-review'),
        'parent_item_colon' => __('Parent Genre:', 'jbros-film-review'),
        'edit_item'         => __('Edit Genre', 'jbros-film-review'),
        'update_item'       => __('Update Genre', 'jbros-film-review'),
        'add_new_item'      => __('Add New Genre', 'jbros-film-review'),
        'new_item_name'     => __('New Genre Name', 'jbros-film-review'),
        'menu_name'         => __('Genres', 'jbros-film-review'),
    );

    $args = array(
        'hierarchical'      => true,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => array('slug' => 'genre'),
    );

    register_taxonomy('genre', 'film_review', $args);
}
add_action('init', 'register_taxonomies');

Now, in your fetch_and_store_movie_data method, you can loop through the genres array and create the corresponding categories using wp_insert_term:

// Assuming $movie_data['genres'] is an array of genre objects
foreach ($movie_data['genres'] as $genre) {
    $term = wp_insert_term($genre['name'], 'genre', array(
        'description' => '',
        'slug'        => sanitize_title($genre['name']),
    ));

    if (!is_wp_error($term)) {
        wp_set_object_terms($post_id, $term['term_id'], 'genre', true);
    }
}

This code will create a new term (category) for each genre in the movie data, and then associate the film_review post with those terms using wp_set_object_terms. After making these changes, the movie genres should be saved as categories for the film_review custom post type. CopyClaude does not have the ability to run the code it generates yet.

Me:I have `single-film_review.php` template for the custom post type in the includes folder of the plugin. What's the best practice approach to adding scss for styling, as well as JavaScript, and scss compiled,both CSS and JavaScript minified and non-blocking?

Here's your homework then - I got Claude started on another subject, but I have not set this one up. Unless you ask Claude specifically it likes to list the steps to get things done and shows a bit of code, but does not get into enough details to actually get it done, unless you ask. It would probably be worth another series to find out how up to date Claude is with setting up taskrunners or build tools for this type of front-end work. You would probably start your prompts with asking Claude to compare or suggest tools based on usage and experience, then continue with getting instructions on how to install and configure the tools. For this plugin it should be straightforward, but on other, larger and complex projects, Claude's help might prove actually helpful, and hopefully not beyond its skill set.

To add SCSS for styling and JavaScript, as well as compiling SCSS to CSS and minifying both CSS and JavaScript in a non-blocking way, you can follow these best practices:

  1. SCSS and CSS:

    • Create a new folder structure inside your plugin folder, e.g., assets/scss for your SCSS files and assets/css for the compiled CSS files.
    • Use a task runner like Gulp or Webpack to compile your SCSS files to CSS. This will allow you to take advantage of features like nesting, variables, and mixins provided by SCSS.
    • During the compilation process, you can also minify the CSS files to reduce their file size and improve load times.
    • Enqueue the minified CSS files in your plugin’s main file using the wp_enqueue_style function, specifying the appropriate dependencies and version number.
  1. JavaScript:

    • Create a new folder structure inside your plugin folder, e.g., assets/js for your JavaScript files.
    • Use a module bundler like Webpack or Rollup to bundle your JavaScript files, including any dependencies from external libraries.
    • During the bundling process, you can minify the JavaScript files to reduce their file size and improve load times.
    • Enqueue the minified JavaScript files in your plugin’s main file using the wp_enqueue_script function, specifying the appropriate dependencies and version number.
  1. Non-blocking CSS and JavaScript:

    • To make your CSS and JavaScript non-blocking, you can use the wp_enqueue_style and wp_enqueue_script functions with the appropriate parameters.
    • For CSS, set the 'media' parameter to ‘none’ and then add an inline script to load the CSS asynchronously after the page has loaded.
    • For JavaScript, set the 'in_footer' parameter to true to load the script before the closing </body> tag.

Here’s an example of how you can structure your plugin’s main file to enqueue the assets:

<?php
/**
 * Plugin Name: Jbros Film Review
 */

// Enqueue styles
function jbros_film_review_enqueue_styles() {
    $plugin_version = '1.0.0'; // Update this to your plugin's version
    $plugin_url     = plugin_dir_url( __FILE__ );

    // Enqueue the minified CSS with non-blocking behavior
    wp_enqueue_style( 'jbros-film-review-styles', $plugin_url . 'assets/css/style.min.css', array(), $plugin_version, 'none' );
    wp_add_inline_script( 'jquery', "jQuery(document).ready(function($) { $('link[rel="stylesheet"][href*="style.min.css"]').attr('media', 'all'); });" );
}
add_action( 'wp_enqueue_scripts', 'jbros_film_review_enqueue_styles' );

// Enqueue scripts
function jbros_film_review_enqueue_scripts() {
    $plugin_version = '1.0.0'; // Update this to your plugin's version
    $plugin_url     = plugin_dir_url( __FILE__ );

    // Enqueue the minified JavaScript in the footer
    wp_enqueue_script( 'jbros-film-review-scripts', $plugin_url . 'assets/js/script.min.js', array( 'jquery' ), $plugin_version, true );
}
add_action( 'wp_enqueue_scripts', 'jbros_film_review_enqueue_scripts' );

In this example, the jbros_film_review_enqueue_styles function enqueues the minified CSS file with a 'media' parameter set to 'none', and then uses an inline script to load the CSS asynchronously after the page has loaded. The jbros_film_review_enqueue_scripts function enqueues the minified JavaScript file in the footer by setting the 'in_footer' parameter to true.

By following these best practices, you can ensure that your SCSS styles are compiled to minified CSS, your JavaScript files are bundled and minified, and both CSS and JavaScript are loaded in a non-blocking way, improving the overall performance and user experience of your plugin.

Coming up

A bit of a short post this was, with less substance. Just to give you a break. Next one isn't really much longer. In part 5 we'll have a look at a few more WordPress development related ideas, the settings page, and also a few more things that did not (yet) end up in the demo code repo. And I think that'll be the end of this series as well.