Plugin schrijven (WordPress): verschil tussen versies

Uit De Vliegende Brigade
Naar navigatie springen Naar zoeken springen
 
(geen verschil)

Huidige versie van 9 dec 2017 om 16:40

Genoeg gehobby'ed! Tijd om zelf een plugin te schrijven!

Plugins zijn programma'tjes om de functionaliteit van een WordPress-site uit te breiden of aan te passen. Plugins werken event-driven, dankzij hooks: Functies van de plugin worden aangeroepen als bepaalde gebeurtenissen zich voordoen op de site.

Aan de slag - Simpele plugin

Kies een naam

Kies een naam, bij voorkeur een unieke naam. Zie de WordPress-plugin page voor namen van bestaande modules

Kies een mapnaam

  • Bepaal de naam van de plugin-map
  • Het is belangrijk dat deze uniek is
  • Als dat een issue kan zijn, dan is het gebruikelijk om de naam te vormen als <maker>-<plugin>. Desalniettemin, als ik nu kijk naar de namen van de plugins van een site waar ik nu aan werk, dan is mikado-core hier het enige voorbeeld van
  • Een plugin-map bevat doorgaans één of meer bestanden. Als er meerdere bestanden zijn, gebruikt WordPress de mapnaam om te kijken of er updates zijn. Mocht je meldingen krijgen dat er updates voor je plugin zijn, terwijl je zeker weet dat je geen updates hebt gemaakt, dan kan het zijn dat er een andere plugin bestaat met dezelfde naam.

Kies een php-bestandsnaam

  • Een plugin heeft in ieder geval één php-bestand nodig, soms the Plugin PHP file genoemd
  • Kies een vrij te bepalen naam voor dat bestand
  • Tip: Gebruik dezelfde naam als voor de map
  • Indien je plugin uit maar één bestand bestaat, gebruikt WordPress de naam van dit bestand om te kijken of er updates zijn

Plugin PHP file - Header

De header bevat diverse soorten informatie over de plugin [1]. Alleen het veld Plugin name is verplicht:

  • Plugin name
  • Plugin URI
  • Description
  • Version
  • Author
  • Author URI
  • License
  • License URI
  • Text domain
  • Domain path.

Voorbeeld:

<?php
/*
Plugin Name:   Plugalot
Plugin URI:    http://devliegendebrigade.nl
Description:   Improving life beyond repair
Version:       20171204
Author:        Jeroen Strompf - De Vliegende Brigade
*/

Activatie- & deactivatie-hooks

Voor activatie van een plugin, gebruik hook

register_activation_hook( __FILE__, 'pluginprefix_function_to_run' );

of gebruik

add_action('init','pluginprefix_function_to_run' );

maar niet alletwee. Deze eerste is te prefereren [2], maar bij mij werkt alleen deze tweede.

Voor deactivatie, gebruik

register_deactivation_hook( __FILE__, 'pluginprefix_function_to_run' );

Voorbeeld:

# Plugin-prefix is plugalot_
#
# Installatie-functie
#######################################################################
#
function plugalot_install()
{
   # Doe van alles en nog wat!
   #
}

# Registreer de installatie-functie
########################################################################
#
add_action('init, 'plugalot_install' );

Verder...

  • Zorg voor een uninstall-procedure [3]
  • Best practices [4]
  • Security [5]
  • Hooks [6]

Hooks

Hooks komen in twee smaken:

  • Actions: Voeg functionaliteit toe, of verander bestaande functionaliteit
  • Filters: Pas gegevens aan gedurende executie.

Standaard zijn er een hoop hooks beschikbaar, maar je kunt daarnaast ook je eigen hooks defineren! En wellicht dat op een dag anderen plugins schrijven voor jouw plugin!

Verder...

  • Administration menu's [7]
  • Shortcodes [8]
  • Settings [9]
  • Metadata [10]
  • Custom Post Types [11]
  • Etc.

Voorbeeld: Hello Dolly

Ik vind de Hello Dolly-plugin rete-irritant, maar nu komt-ie toch nog van pas.

Volledige code

<?php
/**
 * @package Hello_Dolly
 * @version 1.6
 */
/*
Plugin Name: Hello Dolly
Plugin URI: https://wordpress.org/plugins/hello-dolly/
Description: This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words sung most famously by Louis Armstrong: Hello, Dolly. When activated you will randomly see a lyric from <cite>Hello, Dolly</cite> in the upper right of your admin screen on every page.
Author: Matt Mullenweg
Version: 1.6
Author URI: http://ma.tt/
Text Domain: hello-dolly
*/

function hello_dolly_get_lyric() {
	/** These are the lyrics to Hello Dolly */
	$lyrics = "Hello, Dolly
Well, hello, Dolly
It's so nice to have you back where you belong
You're lookin' swell, Dolly
I can tell, Dolly
You're still glowin', you're still crowin'
You're still goin' strong
We feel the room swayin'
While the band's playin'
One of your old favourite songs from way back when
So, take her wrap, fellas
Find her an empty lap, fellas
Dolly'll never go away again
Hello, Dolly
Well, hello, Dolly
It's so nice to have you back where you belong
You're lookin' swell, Dolly
I can tell, Dolly
You're still glowin', you're still crowin'
You're still goin' strong
We feel the room swayin'
While the band's playin'
One of your old favourite songs from way back when
Golly, gee, fellas
Find her a vacant knee, fellas
Dolly'll never go away
Dolly'll never go away
Dolly'll never go away again";

	// Here we split it into lines
	$lyrics = explode( "\n", $lyrics );

	// And then randomly choose a line
	return wptexturize( $lyrics[ mt_rand( 0, count( $lyrics ) - 1 ) ] );
}

// This just echoes the chosen line, we'll position it later
function hello_dolly() {
	$chosen = hello_dolly_get_lyric();
	echo "<p id='dolly'>$chosen</p>";
}

// Now we set that function up to execute when the admin_notices action is called
add_action( 'admin_notices', 'hello_dolly' );

// We need some CSS to position the paragraph
function dolly_css() {
	// This makes sure that the positioning is also good for right-to-left languages
	$x = is_rtl() ? 'left' : 'right';

	echo "
	<style type='text/css'>
	#dolly {
		float: $x;
		padding-$x: 15px;
		padding-top: 5px;
		margin: 0;
		font-size: 11px;
	}
	</style>
	";
}

add_action( 'admin_head', 'dolly_css' );

?>

Map, namen & bestanden

  • De map heet hello-dolly. Aangezien deze meerdere bestanden bevat, wordt de mapnaam gebruikt om te controleren op updates
  • Plugin-php-bestand: hello.php
  • Nog één bestand: readme.txt - Deze is verder niet interessant qua programmeren van de plugin

Header

<?php
/**
 * @package Hello_Dolly
 * @version 1.6
 */
/*
Plugin Name: Hello Dolly
Plugin URI: https://wordpress.org/plugins/hello-dolly/
Description: This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words sung most famously by Louis Armstrong: Hello, Dolly. When activated you will randomly see a lyric from <cite>Hello, Dolly</cite> in the upper right of your admin screen on every page.
Author: Matt Mullenweg
Version: 1.6
Author URI: http://ma.tt/
Text Domain: hello-dolly
*/
  • De eerste regels met @package en @version zijn wellicht voor één of andere packet manager. Je kunt ze ongestraft verwijderen → Deze regels negeren
  • Verder een handjevol regels die met de nodige keywords beginnen. Nix spannends.

Code - Op hoofdlijnen

function hello_dolly()

  • Kiest een regel uit de lyrics
  • Schrijft deze naar het scherm mbv. echo

add_action( 'admin_notices', 'hello_dolly' )

Hiermee wordt de hook geregistreerd. Bij activeren van event admin_notices, wordt de functie hello_dolly aangeroepen.

In Drupal zou je waarschijnlijk de hoofdfunctie (hier hello_dolly) zoiets genoemd hebben als hello_dolly_admin_notices, en deze zou automatisch worden regegistreerd, omdat Drupal voordurend alle bestanden lees op hooks. WordPress doet dit veel efficiënter, al vergt het enig handwerk: Je moet deze add_action-functie zelf toevoegen.

function dolly_css() + add_action

  • De benodigde css-code wordt in een string samengevoegd. De functie dolly_css() stuurt deze css-code mbv. een echo-statement naar het scherm.
  • Statement add_action('admin_head','dolly_css') zorgt dat deze css-functie wordt aangeroepen bij event admin_head. Ik neem aan dat dit event plaatsvindt voordat de admin_notices-event plaatsvindt.

Werking

  • De plugin heeft geen installatie- of deïnstallatie-routine, maar in het menu Plugins heb je wel de gebruikelijke opties Activeren en Deactiveren
  • Als je 'm activeert, wordt het php-bestand gelezen. WordPress doet niets met de functies. De twee add_action-statements worden wel uitgevoerd en geregistreerd als event.

add_action()

De functie add_action registreert de gegeven functie, callback of callback-functie voor de gegeven action, hook of event. Uitvoering wordt verzorgd voor de Action API.

Syntaxis

add_action
(
   string     $tag,
   callable   $function_to_add,
   int        $priority = 10,
   int        $accepted_args =1
)

Parameters

  • $tag (string, required) - Naam van het event
  • $function_to_add (callable, required) - Naam van de callback-functie
  • $priority (int, optional) - Prioriteit. Da's handig, als er meerdere acties bij een bepaald event geregistreert zijn. Standaardwaarde: 10. Hoe lager het nummer, hoe vroeger de uitvoering
  • $accepted_args - Het aantal argumenten dat de callback-functie accepteert. Standaardwaarde: 1

Return

Er wordt altijd true geretourneerd.

Broncode

add_action() is gedefineerd in wp-includes/plugin.php. Dit is de complete code:

378    /**
379	 * Hooks a function on to a specific action.
380	 *
381	 * Actions are the hooks that the WordPress core launches at specific points
382	 * during execution, or when specific events occur. Plugins can specify that
383	 * one or more of its PHP functions are executed at these points, using the
384	 * Action API.
385	 *
386	 * @since 1.2.0
387	 *
388	 * @param string   $tag             The name of the action to which the $function_to_add is hooked.
389	 * @param callable $function_to_add The name of the function you wish to be called.
390	 * @param int      $priority        Optional. Used to specify the order in which the functions
391	 *                                  associated with a particular action are executed. Default 10.
392	 *                                  Lower numbers correspond with earlier execution,
393	 *                                  and functions with the same priority are executed
394	 *                                  in the order in which they were added to the action.
395	 * @param int      $accepted_args   Optional. The number of arguments the function accepts. Default 1.
396	 * @return true Will always return true.
397	 */
398	function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
399	        return add_filter($tag, $function_to_add, $priority, $accepted_args);
400	}

Het enige dat de functie doet, is functie add_filter aanroepen met dezelfde argumenten. Misschien vanwege compatibiliteitsredenen.

De code van add_filter is gelukkig spannender:

106   function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {
107	        global $wp_filter;
108	        if ( ! isset( $wp_filter[ $tag ] ) ) {
109	                $wp_filter[ $tag ] = new WP_Hook();
110	        }
111	        $wp_filter[ $tag ]->add_filter( $tag, $function_to_add, $priority, $accepted_args );
112	        return true;
113	}

Hier wordt de actie toegevoegd aan het global object $wp_filter. Als de hook onbekend, dan wordt-ie toegevoegd aan dit object.

Bronnen