oberonlai/wp-asset

Handy tool for wp_enqueue_scripts.

v1.0.3 2021-11-27 04:15 UTC

This package is auto-updated.

Last update: 2024-11-27 11:16:01 UTC


README

Simple WordPress class for including scripts and styles which is modifed from WP_Register


Requirements


Installation

Install with composer

Run the following in your terminal to install with Composer.

$ composer require oberonlai/wp-asset

WP Option PSR-4 autoloading and can be used with the Composer's autoloader. Below is a basic example of getting started, though your setup may be different depending on how you are using Composer.

require __DIR__ . '/vendor/autoload.php';

use ODS\Asset;

Asset::addScript();

See Composer's basic usage guide for details on working with Composer and autoloading.


Basic Usage

Below is a basic example of enqueue JavaScript and CSS.

require __DIR__ . '/vendor/autoload.php';

use ODS\Asset;

add_action(
	'init',
	function() {
		Asset::addScript(
			array(
				'name'    => 'my_script',
				'url'     => YOUR_PLUGIN_URL . 'assets/js/script.js',
				'deps'    => array( 'jquery' ),
				'version' => YOUR_PLUGIN_VERSION,
				'footer'  => true,
				'ajax'    => false,
				'admin'   => false,
				'params'  => array()
			)
		)

		Asset::addStyle(
			array(
				'name'    => 'my_style',
				'url'     => YOUR_PLUGIN_URL . 'assets/css/style.css',
				'version' => YOUR_PLUGIN_VERSION,
				'deps'    => array(),
			)
		)
	}
);

It is important that call object in the hook of init or WordPress API dosen't work.


Avaiable Attributes


Register JavaScript for Ajax

WP-Asset will help you generate variables ajax_url and ajax_nonce automatically when setting the ajax to true.

Asset::addScript(
	array(
		'name'    => 'my_ajax',
		'url'     => YOUR_PLUGIN_URL . 'assets/js/ajax.js',
		'deps'    => array( 'jquery' ),
		'version' => YOUR_PLUGIN_VERSION,
		'footer'  => true,
		'ajax'    => true,
		'params'  => array(
			'data1'  => 'my_data_1',
			'data2'  => 'my_data_2',
		)
	)
)

After adding script above, you can see JS variables before the scripts.

<script id="my_ajax-js-extra">
var my_ajax = {"data1":"my_data_1","data2":"my_data_2","ajax_url":"https:\/\/local.test\/wp-admin\/admin-ajax.php?action=my_ajax","ajax_nonce":"fead4137e4"};
</script>

You can use ajax_url and ajax_nonce directly in your scripts.

jQuery(function($){
    $(document).ready(function(){ 
        $('#btn').on('click',function(){
			var data = {
				action: "my_ajax",
				nonce: my_ajax.ajax_nonce,
			};
			$.ajax({
				url: my_ajax.ajax_url,
				data: data,
				type: 'POST',
				dataType: "json",
				success: function(data){
					console.log(data);
				},
				error: function(data){
					console.log(data);
				}
			})
        })
    }) 
})