WordPress - Plugin development

From XennisWiki
Jump to: navigation, search

Ausführliche Hilfe, wie du ein WordPress-Plugin erstellst findest auf auf Writing a Plugin.

readme.txt Vorlage

General

Basics

Plugin URL

/**
 * Plugin directory 
 */
define('KÜRZEL_DIR', WP_PLUGIN_DIR . "/" . plugin_basename(dirname(__FILE__)));

Shortcode

In this case the shortcode name is example

/**
 * Output "Hello World"
 *
 * @param  array $atts
 * @return string
 */
add_shortcode(KÜRZEL_example, 'KÜRZEL_example' );
function KÜRZEL_example($atts) {
    $a = shortcode_atts( array(
        'name' => 'World',
	'id' => '200'
    ), $atts);

    return 'Hello '.$a['name'].', '.$a['id'];
}

Usage in WordPress editor

[KÜRZEL_example name='Paul' id='2']

URL parameter

/**
 * Add new URL parameters
 *
 * @param  array $qvars URL parameters
 * @return array $qvars URL parameters
 */
add_filter('query_vars', 'KÜRZEL_add_query_vars');
function KÜRZEL_add_query_vars( $qvars ) {

	// Add parameters to array, e.g.: my_id
	array_push($vars, 'URL-PARAMETER', 'SECOND-URL-PARAMETER');
	return $qvars;
}
// Retrieve a registered parameter, the second value is the default value
get_query_var('my_parameter', 0);

Advanced

Action on plugin activation

/*
 * Register activation hook 
 */
register_activation_hook( __FILE__, 'KÜRZEL_register_activation' );
function KÜRZEL_register_activation() {
	// Action like add database tables here
}

URL rewrite

$KÜRZELRewriteRuleIndex = '(pics|photographer)/([0-9]{1,2})$';
$KÜRZELRewriteRuleIndex2 = 'pics/tag/([^/]+)$';

add_action('wp_loaded','mt_flush_rules');
function mt_flush_rules() {
	global $KÜRZELRewriteRuleIndex;
	global $KÜRZELRewriteRuleIndex2;
	$rules = get_option('rewrite_rules');
	if ( !isset($rules[$KÜRZELRewriteRuleIndex]) || !isset($rules[$KÜRZELRewriteRuleIndex2]) ) {
		global $wp_rewrite;
		$wp_rewrite->flush_rules();
	}
}
add_filter('rewrite_rules_array', 'KÜRZEL_rewrite_rules_array');
function KÜRZEL_rewrite_rules_array($rules){
	global $KÜRZELRewriteRuleIndex;
	global $KÜRZELRewriteRuleIndex2;
	$newrules = array();
	$newrules[$mtRewriteRuleIndex] = 'index.php?pagename=$matches[1]&myId=$matches[2]';
	$newrules[$mtRewriteRuleIndex3] = 'index.php?pagename=tag&myTag=#$matches[1]';
	return $newrules + $rules;
}

Back end

Basics

Add CSS and JS script for admin back end

/*
 * Admin scripts hook
 */
add_action('admin_enqueue_scripts', 'KÜRZEL_admin_enqueue_scripts' );
function KÜRZEL_admin_enqueue_scripts() {
	// Add exemplary css file
	wp_enqueue_style('KÜRZEL-style', plugins_url('admin/css/admin.css', __FILE__));
        // Add jQuery, JavaScript from URL and from file
	wp_enqueue_script('jquery');
	wp_enqueue_script('jquery-ui', 'https://code.jquery.com/ui/1.11.4/jquery-ui.min.js');
	wp_enqueue_script('KÜRZEL-script', plugins_url('admin/js/admin.js', __FILE__ ));
}

Dashboard widget

/*
 * Add a widget to the dashboard.
 *
 * This function is hooked into the 'wp_dashboard_setup' action below.
 */
add_action('wp_dashboard_setup', 'KÜRZEL_wp_dashboard_setup');
function KÜRZEL_wp_dashboard_setup() {
	wp_add_dashboard_widget(
		'mt_dashboard_widget',
		'DASHBOARD-TITLE',
		'KÜRZEL_dashboard_widget_function'
	);	
}
function KÜRZEL_dashboard_widget_function() {
	return 'Hello World'
}

Menu

Further information: Using Wrapper Functions

/**
 * Add plugin pages to menu
 *
 * @return void
 */
add_action('admin_menu', 'KÜRZEL_admin_menu');
function KÜRZEL_admin_menu() {
		
	// Add a new submenu under settings
	add_options_page('PLUGIN-NAME', 'PLUGIN-NAME', 'manage_options', 'KÜRZEL', 'KÜRZEL_options_page');
		
	// Add a new submenu under tools
	add_management_page('PLUGIN-NAME', 'PLUGIN-NAME', 'manage_options', 'KÜRZEL-tool', 'KÜRZEL_management_page' );

	// Add top-level menu item at position 3, with a icon
	add_menu_page('Example', 'Example', 'manage_options', 'KÜRZEL-example', null, 'dashicons-palmtree', 3);
	// Add a sub menu item
	add_submenu_page('mt-example', 'Sub example', 'Sub example', 'manage_options', 'mt-example', 'KÜRZEL_page_example');

}

Pages

Einstellungs-Seite

<?php
/**
 * Displays the page content for the settings submenu
 *
 * @return void
 */
function KÜRZEL_options_page() {
		
	// Must check that the user has the required capability 
	if (!current_user_can('manage_options')) {
		wp_die(__('You do not have sufficient permissions to access this page.'));
	}

	// Now display the settings editing screen
	?>
<div class="wrap">
	<?php screen_icon(); ?>
	<h2>PLUGIN-NAME <?php _e('Settings') ?></h2>
	<form method="post" action="options.php">
		<?php settings_fields('KÜRZEL_options'); ?>
		<?php do_settings_sections('KÜRZEL'); ?>
		<?php
		// get option 'text_string' value from the database
		$options = get_option( 'KÜRZEL_options' ); ?>
		<h3>Picasa</h3>
		<table class="form-table">
			<tr valign="top">
				<th scope="row">Email</th>
				<td><input type="text" name="KÜRZEL_options[username]" value="<?php echo $options['username']; ?>" /></td>
			</tr>
			<tr>
				<th scope="row">Passwort</th>
				<td><input type="password" name="KÜRZEL_options[password]" value="<?php echo $options['password']; ?>" /></td>
			</tr>
		</table>
		<h3>Alben</h3>
		<table class="form-table">
			<tr valign="top">
				<th scope="row"><label for="KÜRZEL_options[access]">Zugriff</label></th>
					<td>
						<select name="KÜRZEL_options[access]" id="KÜRZEL_options[access]">
							<option value="all" <?php selected( $options['access'], 'all' ); ?>>Alle Alben</option>
							<option value="public" <?php selected( $options['access'], 'public' ); ?>>Öffentliche Alben</option>
							<option value="private" <?php selected( $options['access'], 'private' ); ?>>Nur über Link verfügbare Alben</option>
						</select>
					</td>
				</td>
			</tr>
			<tr>
				<th scope="row">Anzeigen</th>
				<td>
					<fieldset>
						<label for="KÜRZEL_options[albums_published]">
							<input name="KÜRZEL_options[albums_published]" type="checkbox" id="KÜRZEL_options[albums_published]" value="1" <?php checked( $options['albums_published'], 1 ); ?> />
						Veröffentlichungsdatum</label><br />
						<label for="KÜRZEL_options[albums_updated]">
							<input name="x11_options[albums_updated]" type="checkbox" id="KÜRZEL_options[albums_updated]" value="1" <?php checked( $options['albums_updated'], 1); ?> />
						Aktualisierungsdatum</label>
					</fieldset>
				</td>
			</tr>
			<tr>
				<th scope="row">Größe des Miniaturbildes</th>
				<td><input type="number" name="KÜRZEL_options[albums_thumb_size]" value="<?php echo $options['albums_thumb_size']; ?>" class="small-text" /> px</td>
			</tr>
			<tr>
				<th scope="row">Datums- und Zeitformat</th>
				<td>
					<input type="text" name="KÜRZEL_options[datetime_format]" value="<?php echo $options['datetime_format']; ?>" />		
					<?php echo "\t<p>" . __('<a href="http://codex.wordpress.org/Formatting_Date_and_Time">Documentation on date and time formatting</a>.') . "</p>\n"; ?>
				</td>
			</tr>
		</table>
		<h3>Fotos</h3>
		<table class="form-table">
			<tr valign="top">
				<th scope="row">Anzahl der Fotos pro Seite</th>
				<td><input type="number" name="KÜRZEL_options[max_results]" value="<?php echo $options['max_results']; ?>" class="small-text" /> Fotos</td>
			</tr>
			<tr>
				<th scope="row">Größe des Miniaturbildes</th>
				<td><input type="number" name="KÜRZEL_options[thumb_size]" value="<?php echo $options['thumb_size']; ?>" class="small-text" /> px</td>
			</tr>
		</table>
		<?php submit_button(); ?>
	</form>
</div>

	<?php
}
?>

Werkzeug-Seite

<?php
/**
 * Display management page
 *
 * @return void
 */
function x11_management_page() {
	?>
<div class="wrap">
	<?php screen_icon(); ?>
	<h2>PLUGIN-NAME Tool</h2>

	[...]
	
	<?php
}
?>
Hilfreiche Funktionen

selected

<option value="all" <?php selected( $options['access'], 'all' ); ?>>Alle Alben</option>

checked

<input name="NAME" type="checkbox" id="ID" value="1" <?php checked( $options['albums_published'], 1 ); ?>

submit_button

<?php submit_button(); ?>

screen_icon

<?php screen_icon(); ?>
Daten speichern

Daten in der Datenbank speichern

/**
 * Add the admin settings and such
 *
 * @return void
 */
add_action('admin_init', 'KÜRZEL_admin_init');
function KÜRZEL_admin_init() {

	// Register settings
	register_setting('KÜRZEL_options', 'KÜRZEL_options', 'KÜRZEL_options_validate');
}
/**
 * Validate user input and output error
 *
 * @param  $input user input
 * @return $valid valid input
 */
function KÜRZEL_options_validate($input) {
		
	$errors = array();
	$valid = array();
		
	while($entry = current($input)) {
		$valid[key($input)] = esc_attr( $entry );
		next($input);
	}
		
	if( $valid['username'] == '' ) {
		$errors['username'] = 'Please enter your username.';		
	}

	// ...

	// Display all errors together
	if( count( $errors ) > 0 ) {
		$err_msg = '';
				
		// Display errors
		foreach( $errors as $err ) {
			$err_msg .= "$err<br><br>"; 
		}
	
		add_settings_error(
			'KÜRZEL_text_string',
			'KÜRZEL_texterror',
			$err_msg,
			'error'
		);
	}
		
	return $valid;
}

Advanced

Display links on plugin page

/**
 * Add plugin's settings link to admin plugins page
 *
 * @param  string $links
 * @param  string $file
 * @return array  $links
 */
add_filter( 'plugin_action_links', 'KÜRZEL_plugin_action_links', 10, 2 );
function KÜRZEL_plugin_action_links( $links, $file ) {
	if ($file == plugin_basename(__FILE__)) {
		$links[] = '<a href="' . admin_url("options-general.php?page=KÜRZEL") . '">'. __('Settings') .'</a>';
	}
	return $links;
}

See also

External links