Skip to content

Instantly share code, notes, and snippets.

@tajidyakub
Last active November 23, 2017 10:11
Show Gist options
  • Save tajidyakub/30a38312c9ef896494b51c35845bce40 to your computer and use it in GitHub Desktop.
Save tajidyakub/30a38312c9ef896494b51c35845bce40 to your computer and use it in GitHub Desktop.
Links, snippets, reminder, collection of point as notes taken during revisit of WordPress Plugin Development #WordPress #Plugin #PHP #References

Notes on WordPress Plugin Development

Plugin in WordPress Framework

Redirect user based on login

Scenario:

  • New user register, a custom user meta is_confirmed created for the user with the value of '0'
  • Plugin send confirmation mail with confirmation link connected to wp options database row on the plugin
  • The plugin add an action which prevent user with is_confirmed false from logging in the action redirect user to plugin's generated notification page and force user to logout
public function login_confirmed_redirect( $redirect_to, $request, $user ) {
		$redirect_to = '/verification/required';
		if ( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
			$user_id = $user->ID;
			// check user meta is_confirmed
			if ( get_user_meta( $user_id, 'is_confirmed', true ) ) {
				return admin_url();	
			} 
			return $redirect_to;
		} else {
			return $redirect_to;
		}
	}
	
add_filter( 'login_redirect', 'login_confirmed_redirect', 10, 3 );

In the page which is accessible through redirection slug we logout user and exit.

if ( $action == 'required' && wp_get_referer() ) {
		?>
			<h1><?php _e( 'Email Confirmation Required', 'member-verify' ) ?></h1>
			<p><?php _e( 'Email address confirmation is <strong>required to continue</strong>, please check your email address for confirmation link', 'member-verify' ) ?></p>
	<?php
		//logout user
		wp_logout();
		exit;
	} 		

Multipart/alternate WP_Mail and Postman-smtp

X-Mailer: Member Verify WP Plugin (https://github.com/tajidyakub/member-verify/)
MIME-Version: 1.0
Content-Type: multipart/alternative;
 boundary="=_2e470917240fbb473f7ec673df526461"
From: "Mailer @TJ" <[email protected]>
Sender: [email protected]
To: [email protected]
Subject: [Notes on {Web}] Please Confirm your Email Address
Date: Thu, 23 Nov 2017 08:50:17 +0000

--=_2e470917240fbb473f7ec673df526461
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable

text content

--=_2e470917240fbb473f7ec673df526461
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable

text/html content

--=_2e470917240fbb473f7ec673df526461--

Multipart can be enabled from filter

add_filter('wp_mail_content_type', 'callback_function');

function callback_function( $content ) {
	return 'multipart/alternative';
}

do_mail_thing()

remove_filter( 'wp_mail_content_type', 'callback_function' );

Note that boundary will be created by WordPress so we don't need to declare one. Recommended to remove filter after sending mails to avoid conflicts with another plugin.

Usable class to enchance wp_mail workflow https://github.com/anthonybudd/WP_Mail

require_once "/path/to/WP_Mail.php";
$email = ( new WP_Mail )
	->( $to )
	->( $subject )
	->( $headers )
	->( $message )
	->send();

Creating virtual WordPress Page

Basically ;

  • Add query var with query var filter
  • Add rewrite rules using the query var as the redirect
  • Use template include filter to serve the page
<?php
/**
 * Register custom query var
 */
function member_verification_query( $vars ) {
	$vars[] = 'memberverify';
  	return $vars;
}
add_filter('query_vars', 'member_verification_query');

/**
 * Init rewrite rule, don't forget to flush
 */
function add_rewrite_memberverify() {
	global $wp_rewrite;
	add_rewrite_tag('%memberverify%', '([^&]+)');
	add_rewrite_rule( '^memberregis/$', 'index.php?memberverify=regis');
	add_rewrite_rule( '^memberverify/$', 'index.php?memberverify=verify');
} 
add_action('init', 'add_rewrite_memberverify' ));
// then create function to flush the rules programmatically

/**
 * Including a template file to display the virtual page
 */
public function include_template( $template ) {
	$plugins = $this->plugins;		
	global $wp_query;		
	$new_tempate = '';
	
	if (array_key_exists( 'verify_action', $wp_query->query_vars ) ) {
			$new_template = $plugins['dir'] . "/public/partials/template-verification-page.php";
			return $new_template;
		}
		return $template;
	}
	
add_filter( 'template_include', 'include_template_memberverify');

The value returned from the callback function has to be returned by the custom template tag function eg we do this in template;

!# template file

// Hook
mv_check_something( $value );

!# function

function mv_check_something( $value ) {
	do_action( 'custom_hook', $value );
	return $value;
}
 

Create custom template hook

Adding action or filter to be use in template via custom action / filter hook. Steps:

  • Define callback function
  • Register the action to WordPress
  • Define callback function to be called by WordPress
<?php
// custom hook function
function custom_function() {
	do_action('custom_function');
}
// register Hook
add_action('custom_function','custom_function_callback');
// callback function
function custom_function_callback(){
	echo "Awesome";
}

Anywhere in the template we can call the function with custom_function()

Create Admin Notice after Plugin Activation

Use set_transient() https://codex.wordpress.org/Function_Reference/set_transient

Usage

<?php set_transient( $transient, $value, $expiration ); ?>

Params

  • $transient required transient name in string sql unescaped 172 char or less, default: none
  • $value required transient value default: none
  • $expiration optional expiration time in second from now, default 0

Implementation

  • set_transient with value true during inside activation hook registered function and 10s expiration time
  • Create callback function to check whether transient exist or not and display a dismissable message if true check with if ( get_transient( 'transient-name' ) ) {}
  • Add action with admin_notices hook add_action('admin_notices', 'display-notice-function')
<?php
/**
 * Display Admin Notice after activation.
 * 
 * Implementation example with set_transient and get_transient
 * with procedural in plugin file.
 */

/* Register activation hook. */
register_activation_hook( __FILE__, 'activation_callback' );

/* Registered activation callback. */
function activation_callback() {
	set_transient( 'pugin-name-transient', true, 10 );
}

/* Add admin notice. */
add_action( 'admin_notices', 'admin_notice_callback' );

/* Admin Notice callback. */
function admin_notice_callback() {
	/* Check transient if exist display and then delete */
	if ( get_transient( 'plugin-name-transient' ) ) {
	?>
		<div class="updated notice is-dismissable">
			<p>Awesome, now you can create your own shortcode with ease, go to <a href="#" title="Shortcode Studio">Shortcode Studio > Shortcodes</a> to begin</p>
		</div>
	<?php
	}
	
	delete_transient( 'plugin-name-transient' );
}

Links API in WP Plugin

add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), 'my_plugin_action_links' );

function my_plugin_action_links( $links ) {
   $links[] = '<a href="'. esc_url( get_admin_url(null, 'options-general.php?page=gpaisr') ) .'">Settings</a>';
   $links[] = '<a href="http://wp-buddy.com" target="_blank">More plugins by WP-Buddy</a>';
   return $links;
}

// or custom more

add_filter( 'plugin_action_links', 'ttt_wpmdr_add_action_plugin', 10, 5 );
function ttt_wpmdr_add_action_plugin( $actions, $plugin_file ) 
{
	static $plugin;

	if (!isset($plugin))
		$plugin = plugin_basename(__FILE__);
	if ($plugin == $plugin_file) {

			$settings = array('settings' => '<a href="options-general.php#redirecthere">' . __('Settings', 'General') . '</a>');
			$site_link = array('support' => '<a href="http://thetechterminus.com" target="_blank">Support</a>');
		
    			$actions = array_merge($settings, $actions);
				$actions = array_merge($site_link, $actions);
			
		}
		
		return $actions;
}

Tutorial and Examples

Tools

PHP_CodeSniffer in Visual Studio Code

Ref: https://tommcfarlin.com/php-codesniffer-in-visual-studio-code/

  • Install Composer, pastikan dapat diakses secara global
  • Tambahkan phpcodesniffer ke dalam requirement $ composer require "squizlabs/php_codesniffer=*"
  • Download wpcs dan letakkan di dalam direktori yang dapat diakses dari direktori project
  • Tentukan direktori wpcs sebagai installed_paths di file konfigurasi phpcs ./vendor/bin/phpcs --config-set installed_paths /path/ke/direktori/wpcs
  • Update settings workspace di visual studio code ⌘ CMD + , masukkan WordPress sebagai standard yang digunakan oleh phpcs "phpcs.enable" : "WordPress"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment