帮我写一个wordpress的插件,随机出现一些歌词之类的句子,在文章的末尾显示

下面是一个简单的WordPress插件示例,该插件会在文章内容末尾随机添加一些预设的歌词或句子。按照以下步骤创建和设置插件:

  1. 在WordPress安装目录下的wp-content/plugins文件夹中创建一个新文件夹,例如命名为random-lyrics-appendix
  2. random-lyrics-appendix文件夹中创建一个主插件文件,例如命名为random-lyrics-appendix.php
  3. 将以下代码复制到random-lyrics-appendix.php文件中:
<?php
/*
Plugin Name: Random Lyrics Appendix
Plugin URI:  https://yourwebsite.com/
Description: A plugin that appends random lyrics or sentences to the end of posts.
Version:     1.0
Author:      Your Name
Author URI:  https://yourwebsite.com/
*/

// 如果这个文件被直接访问,则退出
if (!defined(\'ABSPATH\')) {
    exit;
}

// 定义一个数组来存储随机歌词或句子
$lyrics_array = array(
    \"I\'m just a singer in a rock and roll band.\",
    \"Yesterday, all my troubles seemed so far away.\",
    \"Can\'t stop the feeling!\",
    \"It\'s the eye of the tiger, it\'s the thrill of the fight.\",
    \"Don\'t stop believin\', hold on to that feeling.\",
    // 添加更多歌词或句子...
);

// 函数来获取一个随机的歌词或句子
function get_random_lyric() {
    global $lyrics_array;
    return $lyrics_array[array_rand($lyrics_array)];
}

// 在文章内容末尾添加随机歌词或句子
function append_random_lyric($content) {
    if (is_single() && is_main_query()) { // 确保只在单篇文章中添加
        $random_lyric = get_random_lyric();
        $content .= \'<p><em>\' . esc_html($random_lyric) . \'</em></p>\';
    }
    return $content;
}

// 使用 the_content 过滤器来修改文章内容
add_filter(\'the_content\', \'append_random_lyric\');





保存文件并前往WordPress后台,在插件页面激活“Random Lyrics Appendix”。
访问任何一篇单篇文章,你将在文章末尾看到随机出现的歌词或句子。
请注意,这个插件会在所有单篇文章末尾添加随机歌词或句子。如果你想要更精细的控制(比如排除某些分类的文章或者只在特定页面上显示),你需要修改append_random_lyric函数中的条件判断。

此外,确保插件不会破坏文章内容,并且在使用esc_html函数来转义歌词,这样可以防止潜在的XSS攻击。如果你打算向公众发布这个插件,还需要考虑更多细节,包括确保代码的质量、兼容性和安全性。

发表回复

共有 0 条评论