I am making a plugin that shows a random joke on a custom 404 page via shortcode and it is basically near enough the same as the default hello dolly plugin, where the jokes are hardcoded into the script.
I want to be able to allow users to add their own jokes, maybe pulled from the database via custom post types, or just store it to a file which is pulled into the script (exploded or file_get_contents, i dont know)
I am new to wordpress plugin development, but i know a fair amount of php.
Heres the code i currently have to create an admin page
add_action('admin_menu', 'jokes_admin_add_page');
function jokes_admin_add_page() {
add_options_page('Jokes Page', 'Jokes Menu', 'manage_options', 'plugin', 'jokes_plugin_options_page');
}
// display the admin options page
function jokes_plugin_options_page() {
?>
<div>
<h2>My custom plugin</h2>
Options relating to the Custom Plugin.
<form action="options.php" method="post">
<?php settings_fields('plugin_options'); ?>
<?php do_settings_sections('plugin'); ?>
<input name="Submit" type="submit" value="<?php esc_attr_e('Save Changes'); ?>" />
</form></div>
<?php
}
Don’t use settings api for this.
Register a custom post type, ‘Joke’ see
register_post_type
docsFor each argument, please refer to documentation.
WordPress will add the administration menu for you.
Now your site users can create their own jokes.
At this point you can write a function that take a random joke an return the markup, I’ll use
get_posts
for the scope:And can call this function from a shortcode:
Now you can isert in your posts/pages
[joke]
and a random joke will be shown (if there are some…)However, if you are developing a plugin, is possible that in the theme the
404.php
file does not contain any post or page, so where will you put that shortcode?Probably you can write your own 404 template and use that instead of the theme one, just matter of a filter on
'template_include'
:Using this code, when there is a request that turns into a 404, WordPress will require the ‘404.php’ inside your plugin folder, instead of the one in theme.
In this template you can make use of the
get_random_joke()
function to output the joke, just an example (highly derived form 2013 theme):