不要为此使用设置api。
Register a custom post type, \'笑话“看register_post_type
docs
add_action( \'init\', function () {
$labels = array(
\'name\' => \'Jokes\',
\'singular_name\' => \'Joke\',
\'add_new\' => \'Add New\',
\'add_new_item\' => \'Add New Joke\',
\'new_item\' => \'New Joke\',
\'edit_item\' => \'Edit Joke\',
\'view_item\' => \'View Joke\',
\'all_items\' => \'All Jokea\',
\'search_items\' => \'Search Jokes\',
\'not_found\' => \'No jokes found.\',
\'not_found_in_trash\' => \'No jokes found in Trash.\',
);
$args = array(
\'labels\' => $labels,
\'public\' => true,
\'publicly_queryable\' => false,
\'show_ui\' => true,
\'show_in_menu\' => true,
\'show_in_nav_menus\' => false,
\'query_var\' => false,
\'rewrite\' => false,
\'capability_type\' => \'post\',
\'has_archive\' => false,
\'hierarchical\' => false,
\'supports\' => array( \'title\', \'editor\')
);
register_post_type( \'joke\', $args );
});
对于每个参数,请参阅
documentation.
WordPress将为您添加管理菜单。
现在,您的网站用户可以创建自己的笑话。
此时,您可以编写一个函数,随机取笑并返回标记,我将使用get_posts
对于范围:
function get_random_joke() {
$args = array(
\'post_type\' => \'joke\', // be sure this is exactly 1st arg of register_post_type
\'posts_per_page\' => 1, // one joke is enough
\'orderby\' => \'rand\' // randomly
);
$jokes = get_posts( $args );
if ( empty( $jokes ) ) return; // no jokes, nothing to do
$joke = array_pop( $jokes ); // get posts always returns an array
$out = \'<div id="joke">\';
$out .= sprintf( \'<h3>%s</h3>\', apply_filters(\'the_title\', $joke->post_title) );
$out .= sprintf( \'<p>%s</p>\', apply_filters(\'the_content\', $joke->post_content) );
$out .= \'<div>\';
return $out;
}
并可以从短代码调用此函数:
add_shortcode( \'joke\' , \'get_random_joke\' );
现在,您可以在您的帖子/页面中插入isert
[joke]
并且会随机播放一个笑话(如果有……)
然而,如果您正在开发一个插件,那么在主题中404.php
文件不包含任何帖子或页面,所以您将把那个短代码放在哪里?
也许您可以编写自己的404模板,并使用它来代替主题模板,只需在\'template_include\'
:
add_filter( \'template_include\', function( $template ) {
if ( is_404() ) $template = plugin_dir_path( __FILE__ ) . \'404.php\';
return $template;
} );
使用此代码,当有一个请求变成404时,WordPress将需要404。php在插件文件夹中,而不是在主题中。
在此模板中,您可以使用get_random_joke()
输出笑话的函数,只是一个示例(高度派生自2013主题):
<?php get_header(); ?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<header class="page-header">
<h1 class="page-title">Not found</h1>
</header>
<div class="page-wrapper">
<div class="page-content">
<h2>This is somewhat embarrassing, isn’t it?</h2>
<p>It looks like nothing was found at this location. Maybe try a search?</p>
<?php get_search_form(); ?>
<?php echo get_random_joke(); ?>
</div>
</div>
</div>
</div>
<?php get_footer(); ?>