Automatically Highlight Codes in WordPress With My Performance Optimized Code Snippet

Automatically Highlight Codes in WordPress With My Performance Optimized Code Snippet

In today’s fast-paced world of web development, presenting code snippets in a visually appealing and easily digestible manner is crucial. As developers and tech enthusiasts, we’re always on the lookout for efficient ways to share our knowledge with our audience.

That’s why we’re excited to introduce you to our performance-optimized solution for automatically highlighting code in WordPress. With just a few simple additions to your theme’s functions.php file, you can elevate your website’s user experience and readability without sacrificing page load times. In this blog post, we’ll guide you through the process of integrating Prism JS—a lightweight and customizable syntax highlighter—into your WordPress site.

So, let’s dive in and discover how to make your code snippets shine with minimal effort and maximum impact!

What Is Prism JS And Why Use It?

Prism JS is a powerful and versatile syntax highlighting library that has gained widespread recognition among web developers and designers. It’s designed to make your code snippets more readable and visually appealing by automatically applying color schemes and formatting based on the language used. With its extensible architecture and a wide range of plugins, themes, and language support, Prism JS provides an efficient and highly customizable solution for enhancing your code presentations.

In addition to its impressive performance and small footprint, Prism JS stands out for its ease of integration into any project, whether it’s a simple static website or a complex web application. Its streamlined setup process and thorough documentation make it an excellent choice for developers of all skill levels, allowing them to focus on creating captivating content while ensuring their code examples remain clean and accessible.

In this guide, we’ll walk you through the process of integrating Prism JS into your WordPress website, ensuring that your code snippets are beautifully highlighted and easy to understand for your readers. Let’s begin our journey towards a more engaging and visually striking code presentation!

How To Automatically Highlight Codes in WordPress?

In the following sections, we will share the code that allows you to seamlessly integrate syntax highlighting into your site, ensuring that your content is not only visually appealing but also easier for your visitors to comprehend. Remember, the following code will only load the necessary code and scripts on the “code-snippet” category to ensure enhanced website performance. If you want to enable the functionality everywhere, scroll to the bottom to check the revised code.

<?php

/**

 * Custom functions.php for Prism JS integration.

 *

 * @author ShieldThemes

 * @version 1.0.0

 */



// Check if the function doesn't exist to prevent conflicts.

if ( ! function_exists( 'my_theme_enqueue_prism_assets' ) ) {

    /**

     * Enqueue Prism JS and CSS assets.

     */

    function my_theme_enqueue_prism_assets() {

        if ( is_single() &#038;&#038; has_category( 'code-snippets' ) ) {

            // Define Prism JS and CSS URLs.

            $prism_js_url  = 'https://cdn.jsdelivr.net/npm/[email protected]/prism.min.js';

            $prism_css_url = 'https://cdn.jsdelivr.net/npm/[email protected]/themes/prism.min.css';



            // Register and enqueue Prism JS.

            wp_register_script( 'prism-js', $prism_js_url, array(), '1.27.0', true );

            wp_enqueue_script( 'prism-js' );



            // Register and enqueue Prism CSS.

            wp_register_style( 'prism-css', $prism_css_url, array(), '1.27.0' );

            wp_enqueue_style( 'prism-css' );

        }

    }

    add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_prism_assets' );

}



// Check if the function doesn't exist to prevent conflicts.

if ( ! function_exists( 'my_theme_auto_highlight_code' ) ) {

    /**

     * Automatically add language class to <code> tag inside <pre> tag.

     *

     * @param string $content The post content.

     * @return string The modified post content.

     */

    function my_theme_auto_highlight_code( $content ) {

        // Regular expression to find <code>...</code> blocks.

        $pattern = '/<pre.*?><code.*?>(.*?)<\/code><\/pre>/is';



        // Add language class to <code> tags inside <pre> tags.

        $content = preg_replace_callback( $pattern, 'my_theme_add_language_class', $content );



        return $content;

    }

    add_filter( 'the_content', 'my_theme_auto_highlight_code' );

}



// Add custom field to "code-snippets" category edit form.

function my_theme_add_custom_category_field( $tag ) {

    if ( 'code-snippets' === $tag->slug ) {

        $language_markup = get_term_meta( $tag->term_id, 'language_markup', true );

        ?>

        <tr class="form-field">

            <th scope="row"><label for="language_markup"><?php _e( 'Language Markup', 'your-theme-text-domain' ); ?></label></th>

            <td>

                <input type="text" name="language_markup" id="language_markup" value="<?php echo esc_attr( $language_markup ); ?>" />

                <p class="description"><?php _e( 'Enter the appropriate language class for Prism.js (e.g. "language-php", "language-js", "language-css")', 'your-theme-text-domain' ); ?></p>

            </td>

        </tr>

        <?php

    }

}

add_action( 'category_edit_form_fields', 'my_theme_add_custom_category_field', 10, 2 );



// Save custom field value for "code-snippets" category.

function my_theme_save_custom_category_field( $term_id ) {

    if ( isset( $_POST['language_markup'] ) ) {

        update_term_meta( $term_id, 'language_markup', sanitize_text_field( $_POST['language_markup'] ) );

    }

}

add_action( 'edited_category', 'my_theme_save_custom_category_field', 10, 2 );



// Modify the my_theme_add_language_class function to use the custom field value.

if ( ! function_exists( 'my_theme_add_language_class' ) ) {

    /**

     * Callback function to add language class to <code> tag.

     *

     * @param array $matches The matches from the preg_replace_callback function.

     * @return string The modified <code>...</code> block.

     */

    function my_theme_add_language_class( $matches ) {

        global $post;



        // Extract the code block.

        $code_block = $matches[0];



        // Check if the language class is already added.

        if ( preg_match( '/<code.*?class=.*?language.*?>/', $code_block ) ) {

            return $code_block;

        }



        // Get the language class from custom field value if the post is in the "code-snippets" category.

        if ( has_category( 'code-snippets', $post ) ) {

            $category      = get_category_by_slug( 'code-snippets' );

            $language_class = get_term_meta( $category->term_id, 'language_markup', true );

        } else {

            $language_class = 'language-markup';

        }



        // Add the language class.

        $modified_code_block = preg_replace( '/<code(.*?)>/', '<code$1 class="' . esc_attr( $language_class ) . '">', $code_block );



        return $modified_code_block;

    }

}

Integrating Prism.js with WordPress for Automatic Code Highlighting in the "Code-Snippets" Category

In the following sections we will walk you through integrating Prism.js with WordPress to automatically highlight code snippets within <pre> and <code> tags. We will focus on a specific category, "code-snippets," and demonstrate how to create a custom field that allows users to input the appropriate language class without using any plugins.

Function 1: my_theme_enqueue_prism_assets()

This function is responsible for enqueuing Prism.js and its corresponding CSS assets. It checks if the current post belongs to the "code-snippets" category before enqueuing the assets. This ensures that the assets are loaded only when necessary, improving performance.

Usage:

The my_theme_enqueue_prism_assets() function is hooked to the wp_enqueue_scripts action. It registers and enqueues the Prism.js and CSS files using the wp_register_script() and wp_register_style() functions, respectively.

Function 2: my_theme_auto_highlight_code( $content )

This function automatically adds the language class to the <code> tags within the <pre> tags. It searches for <pre><code>...</code></pre> blocks within the post content and processes them using the my_theme_add_language_class function.

Usage:

The my_theme_auto_highlight_code() function is hooked to the the_content filter. It uses a regular expression to find <pre><code>...</code></pre> blocks and replaces them with the modified version returned by the my_theme_add_language_class function.

Function 3: my_theme_add_language_class( $matches )

This callback function adds the appropriate language class to the <code> tag. By default, it uses the 'language-markup' class but retrieves the custom field value associated with the "code-snippets" category if the post belongs to that category.

Usage:

The my_theme_add_language_class() function is used as a callback for the preg_replace_callback() function within my_theme_auto_highlight_code(). It checks if the language class is already added to the <code> tag and, if not, retrieves the custom field value to use as the language class. It then modifies the <code> tag to include the appropriate language class.

Function 4: my_theme_add_custom_category_field( $tag )

This function adds a custom field called "Language Markup" to the "code-snippets" category edit form. This allows users to input the appropriate language class for Prism.js (e.g., "language-php", "language-js", "language-css").

Usage:

The my_theme_add_custom_category_field() function is hooked to the category_edit_form_fields action. It checks if the current category slug is "code-snippets" and then renders the custom field for the "Language Markup" input.

Function 5: my_theme_save_custom_category_field( $term_id )

This function saves the custom field value for the "code-snippets" category as term metadata. It is executed when the category is updated.

Usage:

The my_theme_save_custom_category_field() function is hooked to the edited_category action. It checks if the language_markup value is set in the $_POST array and then updates the term metadata using the update_term_meta() function.

Custom Field

We have created a custom field called "Language Markup" for the "code-snippets" category. This custom field allows users to input the appropriate language class for Prism.js without using any plugins. The value entered in this field is used as the language class for the <code> tags within the <pre> tags in the posts belonging to the "code-snippets" category.

Working Category

This code snippet is designed to work specifically for the "code-snippets" category. The Prism.js assets are loaded only when a post belongs to this category, and the custom field "Language Markup" is available only in the "code-snippets" category edit form. The language class for the <code> tags is determined based on the custom field value associated with this category.

What If You Want To Enable Code Highlighting Everywhere

If you want to enable code highlighting everywhere without checking the "code-snippets" category, you can modify the functions.php code as follows:



<?php

/**

 * Custom functions.php for Prism JS integration.

 *

 * @author ShieldThemes

 * @version 1.0.0

 */



// Enqueue Prism JS and CSS assets.

if ( ! function_exists( 'my_theme_enqueue_prism_assets' ) ) {

    function my_theme_enqueue_prism_assets() {

        // Define Prism JS and CSS URLs.

        $prism_js_url  = 'https://cdn.jsdelivr.net/npm/[email protected]/prism.min.js';

        $prism_css_url = 'https://cdn.jsdelivr.net/npm/[email protected]/themes/prism.min.css';



        // Register and enqueue Prism JS.

        wp_register_script( 'prism-js', $prism_js_url, array(), '1.27.0', true );

        wp_enqueue_script( 'prism-js' );



        // Register and enqueue Prism CSS.

        wp_register_style( 'prism-css', $prism_css_url, array(), '1.27.0' );

        wp_enqueue_style( 'prism-css' );

    }

    add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_prism_assets' );

}



// Check if the function doesn't exist to prevent conflicts.

if ( ! function_exists( 'my_theme_auto_highlight_code' ) ) {

    /**

     * Automatically add language class to <code> tag inside <pre> tag.

     *

     * @param string $content The post content.

     * @return string The modified post content.

     */

    function my_theme_auto_highlight_code( $content ) {

        // Regular expression to find <code>...</code> blocks.

        $pattern = '/<pre.*?><code.*?>(.*?)<\/code><\/pre>/is';



        // Add language class to <code> tags inside <pre> tags.

        $content = preg_replace_callback( $pattern, 'my_theme_add_language_class', $content );



        return $content;

    }

    add_filter( 'the_content', 'my_theme_auto_highlight_code' );

}



// Add the custom field to the post edit page.

if ( ! function_exists( 'my_theme_add_custom_post_field' ) ) {

    function my_theme_add_custom_post_field() {

        add_meta_box(

            'my_theme_language_markup',

            __( 'Language Markup', 'your-theme-text-domain' ),

            'my_theme_render_custom_post_field',

            'post',

            'side',

            'default'

        );

    }

    add_action( 'add_meta_boxes', 'my_theme_add_custom_post_field' );

}



// Render the custom field on the post edit page.

if ( ! function_exists( 'my_theme_render_custom_post_field' ) ) {

    function my_theme_render_custom_post_field( $post ) {

        wp_nonce_field( 'my_theme_language_markup_nonce', 'my_theme_language_markup_nonce_field' );



        $language_markup = get_post_meta( $post->ID, 'language_markup', true );

        ?>

        <label for="language_markup"><?php _e( 'Language Class:', 'your-theme-text-domain' ); ?></label>

        <input type="text" name="language_markup" id="language_markup" value="<?php echo esc_attr( $language_markup ); ?>" />

        <p><?php _e( 'Enter the appropriate language class for Prism.js (e.g. "language-php", "language-js", "language-css")', 'your-theme-text-domain' ); ?></p>

        <?php

    }

}



// Save the custom field value when the post is saved.

if ( ! function_exists( 'my_theme_save_custom_post_field' ) ) {

    function my_theme_save_custom_post_field( $post_id ) {

        // Verify nonce.

        if ( ! isset( $_POST['my_theme_language_markup_nonce_field'] ) || ! wp_verify_nonce( $_POST['my_theme_language_markup_nonce_field'], 'my_theme_language_markup_nonce' ) ) {

            return $post_id;

        }



        // Check if the current user has permission to edit the post.

        if ( ! current_user_can( 'edit_post', $post_id ) ) {

            return $post_id;

        }



        // Save the custom field value.

        if ( isset( $_POST['language_markup'] ) ) {

            update_post_meta( $post_id, 'language_markup', sanitize_text_field( $_POST['language_markup'] ) );

        }

    }

Conclusion

In this tutorial, we demonstrated how to integrate Prism.js with WordPress to automatically highlight code snippets in a specific category, "code-snippets." We also created a custom field to allow users to input the appropriate language class for Prism.js without using any plugins. By following these steps, you can easily add automatic code highlighting to your WordPress site while maintaining optimal performance.

Buffer Pinterest