markdown 链接,片段,提醒,收集点作为重新访问WordPress插件开发期间的笔记#WordPress #Plugin #PHP #Refere

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 链接,片段,提醒,收集点作为重新访问WordPress插件开发期间的笔记#WordPress #Plugin #PHP #Refere相关的知识,希望对你有一定的参考价值。

# Notes on WordPress Plugin Development


## Plugin in WordPress Framework

- Comment Header https://developer.wordpress.org/plugins/the-basics/header-requirements/
- **Plugin API** - Filters https://codex.wordpress.org/Plugin_API/Filter_Reference
- **Plugin API** - Actions https://codex.wordpress.org/Plugin_API/Action_Reference
- **WordPress Plugin Handbook** https://developer.wordpress.org/plugins/
- WP Hooks Database https://adambrown.info/p/wp_hooks
- **Admin Menu** https://developer.wordpress.org/plugins/administration-menus/
- **Dashicon** https://developer.wordpress.org/resource/dashicons/
- Set trancients for notice after Plugin activation https://shellcreeper.com/how-to-create-admin-notice-on-plugin-activation/
- In depth about admin_notices https://digwp.com/2016/05/wordpress-admin-notices/
- Creating **Options** Page https://codex.wordpress.org/Creating_Options_Pages
- Use **Color Picker** https://make.wordpress.org/core/2012/11/30/new-color-picker-in-wp-3-5/ 
- Creating setting link in plugin list https://codex.wordpress.org/Plugin_API/Filter_Reference/plugin_action_links_(plugin_file_name)
- Check credentials before deactivation and uninstallation https://bryce.se/2014/12/14/quick-look-wordpress-uninstall-php-file/ and https://premium.wpmudev.org/blog/activate-deactivate-uninstall-hooks/ 
- Furthermore on check user and referrer credentials https://github.com/markjaquith/WordPress-Plugin-Installer/blob/master/index.php
- About user's capabilities https://codex.wordpress.org/Roles_and_Capabilities
- Customize column on Post Type listing https://codex.wordpress.org/Plugin_API/Action_Reference/manage_$post_type_posts_custom_column and https://medium.com/devblogcamp/easy-way-to-add-custom-post-type-and-custom-fields-in-wordpress-5f7921c1b0d0
- Custom Metabox for Custom Post Type https://code.tutsplus.com/tutorials/how-to-create-custom-wordpress-writemeta-boxes--wp-20336
- Use acf in the plugin https://www.advancedcustomfields.com/resources/including-acf-in-a-plugin-theme/
- Creating a virtual public facing page, eg. for new member verification page. https://www.exratione.com/2016/04/wordpress-4-create-virtual-pages-in-code-without-page-database-entries/
- Enabling multipart/alternate using wp_mail, and WP_Mail in combination with Postman-smtp. Personal note. [TODO]
- Redirect unconfirmed user; [personal note]

### 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

``` php
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.

```php
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" <noreply@tajidyakub.com>
Sender: noreply@tajidyakub.com
To: akutauuus@gmail.com
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

```php
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](https://github.com/anthonybudd/WP_Mail)

```php
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
<?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;

```php
!# 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
<?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
<?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
<?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

```php

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
- Basic Tutorial in Scotch https://scotch.io/tutorials/how-to-build-a-wordpress-plugin-part-1
- Simple Redirect Plugin http://webcraft.tools/how-to-create-a-simple-wordpress-plugin/
- Simple WordPress Plugin renym http://www.wpexplorer.com/writing-simple-wordpress-plugin/
- Keep Plugin clean with Activation & Deactivation hook and uninstall.php https://premium.wpmudev.org/blog/activate-deactivate-uninstall-hooks/

## Tools 
- WordPress Plugin Boilerplate Generator https://wpbb.me/
- WPGenerator for Custom Post Types and Custom Taxonomy https://generatewp.com/
- Query Monitor WordPress Plugin https://wordpress.org/plugins/query-monitor/

## 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 <kbd>&#8984; CMD</kbd> + <kbd>,</kbd> masukkan `WordPress` sebagai standard yang digunakan oleh phpcs `"phpcs.enable" : "WordPress"`

以上是关于markdown 链接,片段,提醒,收集点作为重新访问WordPress插件开发期间的笔记#WordPress #Plugin #PHP #Refere的主要内容,如果未能解决你的问题,请参考以下文章

在 Markdown 中,链接到页面片段的最佳方式是啥,即#some_id?

自研股票智能分析报警软件更新链接

kali linux maltego-情报收集工具

markdown 在插件激活或插件更新时重新保存永久链接设置。

CMS 垃圾收集流程

ViewPager2 中的片段在返回父片段时被重新创建