JavaScript a AJAX vo WordPress

Ján Bočínec, Webikon s.r.o. | WordCamp Praha 2014

JavaScript a AJAX
vo WordPress

Ján Bočínec (senior programátor)

jan.bocinec@webikon.sk

Webikon s.r.o.

WordPress Slovensko

WP.sk

O čom budeme hovoriť

  1. Registrácia a načítavanie skriptov

Vkladanie JavaScriptu po prvé

header.php		
<head>
	<meta charset="<?php bloginfo( 'charset' ); ?>">
	<title><?php wp_title( '|', true, 'right' ); ?></title>
	<script src="/wp-content/themes/twentyfourteen/
	scripts/my-script.js"></script>
	<?php wp_head(); ?>
</head>

Vkladanie JavaScriptu po druhé

header.php		
<head>
	<meta charset="<?php bloginfo( 'charset' ); ?>">
	<title><?php wp_title( '|', true, 'right' ); ?></title>
	<script src="<?php echo get_template_directory(); ?>/
	scripts/my-script.js"></script>
	<?php wp_head(); ?>
</head>

WP pomocné funkcie

wp_register_script( $handle, $src, $deps, $ver, $in_footer )
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer )

wp_register_style( $handle, $src, $deps, $ver, $media )
wp_enqueue_style( $handle, $src, $deps, $ver, $media )

Vkladanie JavaScriptu správne

functions.php
function webikon_load_scripts() 
{
	wp_register_script( 'my-script', 
	get_template_directory_uri() . '/scripts/my-script.js' );
	if ( is_page() )
		wp_enqueue_script( 'my-script' ); 
}
add_action( 'wp_enqueue_scripts', 'webikon_load_scripts' );
function webikon_load_scripts( $hook ) 
{
	// nenačítavame na klasických admin stránkach
	if( $hook != 'edit.php' && $hook != 'post.php' 
	&& $hook != 'post-new.php' ) return;

	wp_enqueue_script( 'my-script' ); 
}
add_action( 'admin_enqueue_scripts', 'webikon_load_scripts' );
add_action( 'login_enqueue_scripts', 'webikon_load_scripts' );

Používame

add_action( 'wp_enqueue_scripts', 'webikon_load_scripts' );
add_action( 'admin_enqueue_scripts', 'webikon_load_scripts' );
add_action( 'login_enqueue_scripts', 'webikon_load_scripts' );

...nie!!!

add_action( 'wp_head', 'webikon_load_scripts' );
add_action( 'wp_print_[scripts|styles]', 'webikon_load_scripts' );
add_action( 'admin_init', 'webikon_load_scripts' );
function webikon_load_scripts() 
{
	wp_enqueue_script( 'my-script', 
	plugins_url( 'js/script-file.js', __FILE__ ),
	array( 'dependency' ),
	'1.0',
	true );
}
add_action( 'wp_enqueue_scripts', 'webikon_load_scripts' );

Skripty a "shortcode"

function webikon_shortcode( $atts ) 
{
	wp_enqueue_script( 'my-script' ); 

	return "Toto je WS shortcode!";
}
[ws]
add_shortcode( 'ws','webikon_shortcode' );

Skripty a "widget"

class webikon_Widget extends WP_Widget {
	Klasické metódy pre widget...	
	public function widget( $atts ) 
	{
		wp_enqueue_script( 'my-script' ); 
		Obsah widgetu...
	}
}
register_widget( 'webikon_Widget' );

Ako zruším/nahradím skript?

wp_deregister_script( $handle )
wp_dequeue_script( $handle )

wp_deregister_style( $handle )
wp_dequeue_style( $handle )

wp_script_is( $handle, $list = 'enqueued' )
wp_style_is( $handle, $list = 'queued|registered|done|to_do' )

Prečo to je dobré?

Stojí to za tie extra riadky v kóde?

Určite áno!

Pribalené knižnice

Skript Handle Dependency
jQuery UI Core jquery-ui-core jquery
jQuery UI Accordion jquery-ui-sortable jquery
jQuery UI Datepicker jquery-ui-datepicker jquery
MediaElement.js wp-mediaelement jquery
Iris (Colour picker) iris jquery
Backbone.js (MVC) backbone -

...a desiatky ďalších...wp_enqueue_script

functions.php
function webikon_load_scripts() 
{
	if ( ! wp_is_mobile() )
		wp_enqueue_script( 'thickbox' ); 

	if ( is_user_logged_in() )
		wp_enqueue_script( 'swfupload' );
}
add_action( 'wp_enqueue_scripts', 'webikon_load_scripts' );
function webikon_load_scripts() 
{
	wp_deregister_script( 'jquery' ); 
	$src = '//ajax.googleapis.com/
	ajax/libs/jquery/2.1.0/jquery.min.js';
	wp_register_script( 'jquery', $src, array(), '2.1.0' );

	wp_enqueue_script( 'jquery' );
}
add_action( 'wp_enqueue_scripts', 'webikon_load_scripts' );

Lokalizácia skriptov

Posielajte dáta zo sveta PHP do sveta JS

wp_localize_script( $handle, $name, $data )
wp_localize_script( 
		'nazov-skriptu', 
		'unikatny_nazov_js_objektu',
		array('dáta budú enkódované cez "json_encode"') 
		)
function webikon_enqueue() 
{
	wp_enqueue_script( 'title-change', 
	plugins_url( 'title-change.js', __FILE__ ) );

	wp_localize_script( 'title-change', 'nejaky_js_objekt', 
		array(
			'title_change' => __('Title in English', 
									'translate_domain')
		));
}
jQuery(document).ready(function($) {
    $('h2').html(nejaky_js_objekt.title_change);
});
wp_localize_script( 'user-data', 'user_data', 
		array(
			'user_id' => get_current_user_id(),
			'user_user_email' => $user_email,
			'user_login' => $user_login,
			...
		));
JS
console.log( user_data.user_id )

AJAX funkcia v PHP

function webikon_like_action( ) 
{
  if( ! empty ($_POST['post_id'] ) ) 
  {
    update_post_meta( $_POST['post_id'], 'post_like', +1 );
  }

  die();
}

AJAX JavaScript

var post_data = {'post_id': post_id,'action': 'like',...};

jQuery.ajax({
	data: post_data,
	type: "POST",
	url: ajaxurl,
	success: function( response ) { // get the party started }
});

ajaxurl funguje len vo WP admine!

wp_localize_script( 'my-script', 'my_script', 
		array(
			'ajaxurl' => admin_url( 'admin-ajax.php' )
		));
JS
console.log( my_script.ajaxurl );

AJAX funkcia v PHP

Prihlásení používatelia
add_action( 'wp_ajax_like', 'webikon_like_action' );
Neprihlásení používatelia
add_action( 'wp_ajax_nopriv_like', 'webikon_like_action' );

wp_ajax_ACTION

wp_ajax_nopriv_ACTION

AJAX dáta v XML alebo JSON

$x = new WP_Ajax_Response( array(
    'what' => 'like',
    'id' => $id,
    'data' => $id ? $data : '',
    'supplemental' => $supplemental
) );
$x->send();
ALEBO
echo json_encode( $data );

Vrátená hodnota je vždy 0 alebo -1

WTF???

Nie, chyba nie je v Matrixe!

is_admin() === TRUE

Optimalizácia a testovanie

Zdá sa vám ten WP AJAX nejaký pomalý?

Máte pravdu!

Vždy sa načítava celé WP jadro!

ini_set('html_errors', 0);
define('SHORTINIT', true);

require '../../../../wp-load.php';
require( ABSPATH . WPINC . '/formatting.php' );
require( ABSPATH . WPINC . '/meta.php' );
require( ABSPATH . WPINC . '/post.php' );
wp_plugin_directory_constants();
...a ďalšie veci...

Woooooooot!

(function(b){var a={add:"ajaxAdd",del:"ajaxDel",dim:"ajaxDim", process:"process",recolor:"recolor"}, c;c={settings:{url:ajaxurl, type:"POST",response:"ajax-response",what:"",alt:"alternate",altOffset:0, addColor:null,delColor:null, dimAddColor:null,dimDelColor:null, confirm:null,addBefore:null, addAfter:null,delBefore:null,delAfter:null , dimBefore:null,dimAfter:null},nonce:function(g,f){var d=wpAjax. unserialize(g.attr("href"));return f.nonce||d._ajax_nonce
define('SCRIPT_DEBUG', true);

Nástroje a zdroje

Ďakujem!

Otázky?

Ján Bočínec (senior programátor)

jan.bocinec@webikon.sk

Webikon

webikon.sk