<?php
/*
Plugin Name: Custom output
Description: A module to test the custom output. To test: http://your_wordpress_site.com/customop_uri_path
Version: 1.0
Author: Danilo Silva
Author URI: http://danilocgsilva.me
*/
// Write a new permalink entry on code activation
register_activation_hook( __FILE__, \'customop_activation\' );
function customop_activation() {
customop_custom_output();
flush_rewrite_rules(); // Update the permalink entries in the database, so the permalink structure needn\'t be redone every page load
}
// If the plugin is deactivated, clean the permalink structure
register_deactivation_hook( __FILE__, \'customop_deactivation\' );
function customop_deactivation() {
flush_rewrite_rules();
}
// And now, the code that do the magic!!!
// This code create a new permalink entry
add_action( \'init\', \'customop_custom_output\' );
function customop_custom_output() {
add_rewrite_tag( \'%customop_uri_path%\', \'([^/]+)\' );
add_permastruct( \'customop_uri_path\', \'/%customop_uri_path%\' );
}
// The following controls the output content
add_action( \'template_redirect\', \'customop_display\' );
function customop_display() {
if ($query_var = get_query_var(\'customop_uri_path\')) {
header("Content-Type: text/plain");
echo \'This is my custom content!!!!\';
exit; // Don\'t forget the exit. If so, WordPress will continue executing the template rendering and will not fing anything, throwing the \'not found page\'
}
}
用这个代码创建一个插件。激活插件并在浏览器中测试键入
http://your_wordpress_site.com/customop_uri_path.
registers函数处理permalink结构,仅在插件激活或停用时执行(在不再使用插件的情况下,清除permalinks条目)。
真正的魔法是通过以下代码实现的。有两个函数:一个在插件激活中用于创建新的重写规则并添加永久链接条目,另一个用于控制输出显示。如果之前创建了自定义uri路径,则get\\u query\\u var函数将扫描uri参数。如果是这样,那么它将执行代码来编写自定义输出。不要忘记最后一个出口,否则它将落在找不到的内容页中。
扫描代码中是否出现“customop\\u uri\\u path”,以自定义自定义自定义输出的uri地址。老实说,我还是不明白add_rewrite_tag
和add_permastruct
参数。因此,只需替换为您自己的uri路径。
此外,请确保您的apache重写模块工作正常,并且您的WordPress安装设置为使用永久链接,否则您将看不到该模块工作正常。