[Simple tutorial for WordPress plugin development]Display random lyric at the homepage

Plugins are a very important way for WordPress to customize your blog site. One of the most familiar plugins to WordPress users is probably Hello Dolly – which comes with the WordPress installation and is used as a tutorial to teach users how to use and develop plugins. Once enabled it will display Hello Dolly lyrics randomly in the top right corner of the backend page.

The plugin itself has no practical use, but I enabled it for the purpose of having fun. After a while the idea arose to change the lyrics to what I wanted, such as my own playlist, Vocaloid China and display them in the homepage instead of admin interface.

Hello, Dolly

I downloaded Hello Dolly for such purpose. Hello Dolly contains a PHP file with the following code (part of the code has been omitted).

<?php
/**
 * @package Hello_Dolly
 * @version 1.7.2
 */
/*
<?php
/**
 * @package Hello_Dolly
 * @version 1.7.2
 */
/*
Plugin Name: Hello Dolly
Plugin URI: http://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.7.2
Author URI: http://ma.tt/
*/

function hello_dolly_get_lyric() {
	/** Lyrics. Omitted. */
	$lyrics = "Hello, Dolly
";

	// 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();
	$lang   = '';
	if ( 'en_' !== substr( get_user_locale(), 0, 3 ) ) {
		$lang = ' lang="en"';
	}

	printf(
		'<p id="dolly"><span class="screen-reader-text">%s </span><span dir="ltr"%s>%s</span></p>',
		__( 'Quote from Hello Dolly song, by Jerry Herman:', 'hello-dolly' ),
		$lang,
		$chosen
	);
}


// 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() {
	echo "
        <!-- CSS format. Omitted.-->
	<style type='text/css'>
	#dolly 
	</style>
	";
}

add_action( 'admin_head', 'dolly_css' );

The plugin is mainly divided into two parts: the comment that introduces the basic information and the code behind it. WordPress reads the header comment to get the basic information of the plugin, such as the plugin name, author, introduction, etc., which only needs to be filled in accordingly.

The part of the code where you can see the random lyric interception is still very simple and straightforward. The function hello_dolly_get_lyric() selects a random line of lyrics; hello_dolly() prints out the lyrics returned by hello_dolly_get_lyric() with the original composition information. dolly_css() is responsible for placing the necessary css to manage the way the lyrics are displayed. Finally the plugin is mounted using wp’s hook (add_action), which is triggered to execute when the admin interface is loaded.

Hooks hooks are the key to plugins being able to add functionality without changing the kernel. plugins in Wp are mainly divided into two types: action and filter. the action type inserts a piece of code into the specified time point for execution. For example, after the page is loaded, a greeting window pops up before the body is loaded; the filter outputs the input data after certain processing, such as having all the body content appended with a paragraph about the author before it is displayed. Here we take action type as an example, we write the callback function first, and then mount our callback function by add_action().

In the WordPress development documentation, the add_action method is described as follows.

add_action( string $hook_name, callable $callback, int $priority = 10, int $accepted_args = 1 )

The function has four basic parameters: the name of the hook used, the callback function, the callback priority and the number of parameters accepted. The hook name is a mandatory parameter and determines where the function is inserted. Examples are save_post (after the post has been saved), admin_head (backend page header), etc. The second parameter is the callback function we want to pass in. The last two parameters are optional and are the priority and the number of parameters. The priority determines the order of execution, the smaller the number the higher the priority, the default is 10.

// 将插件设置为管理界面时执行
add_action( 'admin_notices', 'hello_dolly' );

With customized themes

After figuring out the basics of how plugins work in wp, we can get started. The personalized theme (using the argon used on this page) provides several places on the home page where lyrics can be placed, such as the subtitle, the motto bar and the announcement bar. Here is the example of the motto bar. You can view the theme code by going to the Appearance-Theme Editor page in the WP backend administration interface. In theme Argon, the motto bar is located in the sidebar of the page, as shown in the figure.

♪ 总是想太多还不如什么都别想 ♪

In the sidebar sidebar.php of the theme file, include the following code to control the display of the subheadings/grams on the left.

<?php 
	$sidebar_subtitle = get_option('argon_sidebar_banner_subtitle'); 
	if ($sidebar_subtitle == "--hitokoto--"){
		$sidebar_subtitle = "<span class='hitokoto'></span>";
	}
?>
<?php if ($sidebar_subtitle != '') { /*左侧栏子标题/格言(如果选项中开启)*/?>
	<span class="leftbar-banner-subtitle text-white"><?php echo $sidebar_subtitle; ?></span>
<?php } /*顶栏标题*/?>

The theme will get our pre-set motto from the WordPress data table using the get_option() method. The custom theme does not provide hooks for us to modify the content of the banner field here, so if we don’t modify the theme file we have to do it to the wp data table. the Option data table is a separate data table in the WordPress database that stores custom data for the site and is open for users and plugins to modify and edit. So a possible idea is to change the value of argon_aidebar_banner_subtitle in the data table to what we want after each refresh, before the page is displayed.

WordPress provides the following functions to manipulate the option data table in a single site(Cited from wpzhiku.com/understanding-working-wordpress-options-table):

函数参数备注
add_option()$option,
$value,
$deprecated,
$autoload
only $option  is required.
delete_option()$optionDelete all records of this item.
get_option()$option,
$default
$default (Optional) Return this value if the option is not available.
update_option()$option,
$new_value
$new_value is the new value of option_value 
add_site_option()$option
$value
Similar to add_option() ,but in all sites.
delete_site_option()$optionSimilar to delete_option(), but in all sites.
get_site_option()$option
$default
$use_cache
和 get_option() , but used in multisite mode.
update_site_option()$option$value和 update_option() , but used in multisite mode.

The code implementation of the plug-in is as follows.

<?php
/**
 * @package VC_lyrics_random_display
 * @version 2012.7.12
 */
/*
Plugin Name: Singsingsing-主页随机显示vc歌词
Plugin URI: https://ltyxh.com
Description: 博客主页每次刷新显示一句随机VC歌词。适用于所有主题,自行修改插件即可。【默认为argon主题/显示位置博客格言区】世界很大很乱,地球在转,数不清的各种悲和欢。总是想太多还不如什么都别想。
Author: 珞林
Version: 2012.7.12
Author URI: https://ltyxh.com/
*/

function vc_get_lyric() {
    define('MYPLUGINNAME_PATH', plugin_dir_path(__FILE__) );
	$lyrics = file_get_contents(MYPLUGINNAME_PATH . 'vc_lyrics.txt');
	$lyrics = explode( "\n", $lyrics );
	return wptexturize( $lyrics[ mt_rand( 0, count( $lyrics ) - 1 ) ] );
}


function vc_lyric_change_option() {
	$chosen = vc_get_lyric();
	$chosen = str_replace(array(' ','&nbsp;'),'',$chosen);
	//修改数据表
	update_option( 'argon_sidebar_banner_subtitle', $chosen);
}

//execute when the plugins_loaded action is called.
add_action( 'plugins_loaded', 'vc_lyric_change_option' );

With the large amount of alternative lyrics, it is obviously not wise to cram them into the variable initialization statements of the code, nor is it convenient to modify them later. So here we put the lyrics in a separate file vc_lryics.txt. We have mounted the function to “plugins_loaded”, which means that it is executed when the page loads the plugin. Note that when reading vc_lyrics.txt, we need to get and add the wp plugin path in front of the file name, otherwise the file will not be found and an error will be reported.

As for the demonstration, readers can go back to the Chinese home page of the blog to experience it. In Argon mobile to view the sidebar need to click the top left corner. Have fun!

No Comments

Send Comment Edit Comment


|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
洛天依九周年
颜文字
Emoji
小恐龙
花!
Previous
Next