Syntax Highlighting with Prismjs in WordPress

  1. Select the language in and download the prism.css & prism.js
  2. I’m using GeneratePress Child Theme, and i had manually create css & js directory in generatepress_child
/var/www/html/wordpress/wp-content/themes# ls generatepress*
404.php       content-link.php  content-single.php  footer.php     inc        no-results.php  rtl.css         search.php        single.php
archive.php   content-page.php  css                 functions.php  index.php  page.php        screenshot.png  sidebar-left.php  style.css
comments.php  content.php       fonts               header.php     js         readme.txt      searchform.php  sidebar.php       style.min.css

css  functions.php  js  screenshot.png  style.css
  1. Upload the prism.css & prism.js to wordpress server with SCP
#Copy the uploaded prism.js & prism.css 
cp prism.js /var/www/html/wordpress/wp-content/themes/generatepress_child/js
cp prism.css /var/www/html/wordpress/wp-content/themes/generatepress_child/css 
#Grant ownership to www-data 
sudo chown -R www-data:www-data /var/www/html/wordpress/wp-content/themes/generatepress_child/js/prism.js
sudo chown -R www-data:www-data /var/www/html/wordpress/wp-content/themes/generatepress_child/css/prism.css
#Assign full permission to owner (www-data), and remove write permission for other users
chmod -R 755 /var/www/html/wordpress/wp-content/themes/generatepress_child/js/prism.js
chmod -R 755 /var/www/html/wordpress/wp-content/themes/generatepress_child/css/prism.css
  1. Add the following PHP Codes to /var/www/html/wordpress/wp-content/themes/generatepress_child/functions.php
function add_prism() {
        wp_register_style('prismCSS', get_stylesheet_directory_uri() . '/css/prism.css');
        wp_register_script('prismJS', get_stylesheet_directory_uri() . '/js/prism.js');

        global $post, $wp_query;
        $post_contents = '';
        if ( is_singular() ) {
                $post_contents = $post->post_content;
        } elseif ( is_archive() || (is_front_page() && is_home())) {
                $post_ids = wp_list_pluck( $wp_query->posts, 'ID' );
                foreach ( $post_ids as $post_id ) {
                        $post_contents .= get_post_field( 'post_content', $post_id );
        if ( strpos( $post_contents, '<code class="language-' ) !== false ) {
add_action('wp_enqueue_scripts', 'add_prism');

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top