Skip to content

Instantly share code, notes, and snippets.

@leomuniz
Last active November 20, 2022 00:07
Show Gist options
  • Save leomuniz/6da03e6a173a2a6f14d2b63eadf2bc9d to your computer and use it in GitHub Desktop.
Save leomuniz/6da03e6a173a2a6f14d2b63eadf2bc9d to your computer and use it in GitHub Desktop.
Basic Javascript file template for WordPress with jQuery
var page = ( function( document, $ ) {
var app = {
/**
* is_ready() method - Executes the method received when the document is ready.
*
* @since {VERSION}
*
* @param {function} callback Function to be executed when the document is ready.
*/
is_ready: function( callback ) {
$(document).ready( function() {
callback();
});
},
/**
* setEvents() method - Set events to be executed
*
* @since {VERSION}
*/
setEvents: function() {
alert( 'code' );
}
};
return app;
})( document, jQuery );
page.is_ready( page.setEvents );
/**
* Enqueue scripts and styles for admin side.
*
* @since 1.0.0
*/
public function admin_enqueue_scripts() {
// wp_get_environment_type() = 'production' by defaul.
// To change it, define the 'WP_ENVIRONMENT_TYPE' constant on wp-config.php
// Example: define( 'WP_ENVIRONMENT_TYPE', 'local' );
$min = wp_get_environment_type() !== 'production' ? '' : '.min';
if ( get_post_type() === 'post' ) { // To enqueue only where it's being used.
wp_enqueue_style( 'ctp-edit-page-css', THEME_CSS_URL . "cpt-edit-page{$min}.css", [], THEME_VER, 'all' );
wp_enqueue_script( 'cpt-edit-page-js', THEME_JS_URL . "cpt-edit-page{$min}.js", [ 'jquery' ], THEME_VER, false );
}
}
add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] );
/**
* Enqueue scripts and styles for frontend side.
*
* @since 1.0.0
*/
public function wp_enqueue_scripts() {
// wp_get_environment_type() = 'production' by defaul.
// To change it, define the 'WP_ENVIRONMENT_TYPE' constant on wp-config.php
// Example: define( 'WP_ENVIRONMENT_TYPE', 'local' );
$min = wp_get_environment_type() !== 'production' ? '' : '.min';
if ( get_post_type() === 'post' ) { // To enqueue only where it's being used.
wp_enqueue_style( 'ctp-edit-page-css', THEME_CSS_URL . "cpt-edit-page{$min}.css", [], THEME_VER, 'all' );
wp_enqueue_script( 'cpt-edit-page-js', THEME_JS_URL . "cpt-edit-page{$min}.js", [ 'jquery' ], THEME_VER, false );
}
}
add_action( 'wp_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] );

Javascript basic file template for WordPress with enqueue functions to add to both admin area or frontend and minification .min according to the site environment.

Note:

If you need to delay the moment to enqueue the style/script, just use wp_register_script or wp_register_style.

Then, when the time comes, enqueue it using wp_enqueue_script( 'script-handle' ); or wp_enqueue_style( 'style-handle' );. Handle is the first param of both the register and enqueue functions.

Example: Add CSS or JS file only if a shortcode is present.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment