Savings settings in a custom PHP plugin for WordPress - php

First, I'd like to pre-emptively apologize for doing anything naive or foolish. I'm a novice programmer, but I'm trying to learn. Right now, I'm trying to develop a plugin for wordpress as part of my internship. The plugin does what it needs to do for the most part, but I just can't seem to make the settings page work the way I want. I know the initialization part of the plugin is working properly, but I'm having trouble with using the settings page. Specifically, I don't where or how to use _POST in order to save the information. I also don't where to place the update_option function call after I've received the information from the settings page. Here's my code right now:
add_action( 'admin_menu', 'menu' );
add_action( 'admin_init', 'plugin_admin_init' );
function plugin_admin_init() { // whitelist options
register_setting( 'plugin_options', 'plugin_options', 'plugin_options_validate' );
add_settings_section('plugin_main', 'Main Settings', 'plugin_section_text', 'plugin');
add_settings_field('plugin_text_string', 'REE View Count Settings', 'plugin_setting_string', 'plugin', 'plugin_main');
}
function menu() {
add_options_page( 'REE View Count Options', 'REE View Count', 'manage_options', 'plugin', 'plugin_options_page' );
}
// generates the settings web page
function plugin_options_page() {
echo '<div class="wrap">';
echo '<h2>Options</h2>';
echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post">';
// In the line above, I don't know what to put. The file name of the plugin?
// The URL of the settings page on the admin page? Or what I have currently?
// Both the first and last options bring up a 404 page.
settings_fields('plugin_options');
do_settings_sections('plugin');
echo '<input name="Submit" type="submit" value="' . esc_attr_e('Save Changes') . '" />';
echo '</form>';
//update_option('plugin_options', $_POST['plugin_options']);
// Where should I try to update the option? And how?
echo '</div>';
}
//from add_settings_section parameter 3, in plugin_admin_init
function plugin_section_text() {
echo '<p>Main description of this section here.</p>';
}
//Function from 3 paramter of add_settings_field in plugin_admin_init that outputs input HTML
function plugin_setting_string() {
$options = get_option('plugin_options');
echo 'value of options is: ' . $options;
echo "<input id='plugin_text_string' name='plugin_options' size='40' type='text'
value='{$options}' />";
}
//Validation function from register_setting in plugin_admin_init
function plugin_options_validate($input) {
echo "this is input: " . $input;
$newinput = trim($input);
if(!preg_match('/^[0-9]+$/', $newinput)) {
$newinput = 10;
}
update_option('plugin_options', $newinput);
return $newinput;
}
Note: I don't actually use these exact function/variable names - I have them prefixed with the actual plugin name.
Can you help me? I want to take the information the admin inputs into the settings page and update the database with the that information (which in this case is just a single number). I understand that I need to use PHP _POST, but I don't know how. Furthermore, I don't where to post to, because when I use action="the_file_name.php," I get a 404 error upon submission. What should the action of the form be so that I can use the information that I got from the admin submission and use it for later? And after I do that, how do update the setting? And by how, I mean where do I place update_option? I apologize if this seems rambly or vague - I feel like I'm somewhat over my head.
If it helps, I've been building this settings page in the same file as the plugin itself, with the help of this guide: http://ottopress.com/2009/wordpress-settings-api-tutorial/
Unfortunately, I don't see anything in that guide that speaks of updating information, just creating the page itself.

You want to point to action="options.php". It handles updating the values. Check out the following links to get more detailed info.
http://planetozh.com/blog/2009/05/handling-plugins-options-in-wordpress-28-with-register_setting/
http://www.sitepoint.com/wordpress-options-panel/

Related

Custom "Post Author" Input Instead of Dropdown

I have a site with over 20,000 users. Occasionally I need to update the author of a post. However, the sheer amount of users makes the "Author" metabox on the edit post screen unusable. I'm trying to make a custom box where I can input the desired author's ID and change the post author to that ID. Ideally, I would like to do this within the box itself, rather than by way of saving/updating the post.
Here's my custom meta box code:
//Get the post data
$id = get_the_ID();
$author_id= $post->post_author;
<div class="update-author">
<p><strong>Current Author ID:</strong> <?php echo $author_id;?></p>
<p><strong>CHANGE AUTHOR ID TO:</strong></p>
<form id="update-author-form" method="post" action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" >
<input type="hidden" name="action" value="update_author_form">
<input type="hidden" name="post-id" value="<?php echo $id; ?>">
<input type="number" id="update-author-id" name="update-author-id" value="" />
<button id="update-author-button" class="button button-primary button-large">Update Author ID</button>
</form>
</div>
Next, I have my form function built as follows:
function handle_update_author_form() {
$post_id = $_POST['post-id'];
$update_id = $_POST['update-author-id'];
$my_post = array(
'ID' => $post_id,
'post_author' => $update)_id,
);
wp_update_post( $my_post );
}
At this stage, my form button does nothing but refresh the page and send it to the posts screen (I know, I need to change the redirect URL).
Like in comments - I would go for a another approach of removing the original meta_box and replacing it with a new one - or alternatively just use a JS to turn the dropdown list into a searchable field ( for example the excellent select2 plugins - but have others - and also pure JS is quite easy - see example below )
Anyhow - in your code that you posted you are missing the hook where you can apply and invoke your code, for example:
'add_action( 'save_post', 'handle_update_author_form', 10, 1 ); '
Have a look at wp filters and actions.
The suggested (simple) JS solution :
Now, for the simple approach of just using JS to pseudo-search inside the dropdown and therefor there is no real need to interfere with the query or post injections.....
myPlugin.php / myTHeme,php
function admin_enqueue_scripts_callback(){
// We are using select2.js from CDN here ..
//This will add Select2 CSS
wp_enqueue_style( 'select2-css', 'https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css', array(), '4.1.0-rc.0');
////This will add Select2 JS
wp_enqueue_script( 'select2-js', 'https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js', 'jquery', '4.1.0-rc.0');
// Now we need a JavaScript file to initialize the Select2 elements
// here it is staged as a plugin - but a theme would be the same .
wp_enqueue_script( 'select2-init', '/wp-content/plugins/select2-init.js', 'jquery', '4.1.0-rc.0');
}
add_action( 'admin_enqueue_scripts', 'admin_enqueue_scripts_callback' );
select2-init.js
// initialize select2 on author dropdown field with jQuery
jQuery(document).ready(function($) {
$('#post_author_override').select2();
});
voilà !
At this point you will have the pseudo-search implemented that would resolve your problem in a practical way without any new ->queries or $objects and with minimum coding.
Possible / potential caveats
I am not sure what would be the efficiency of filtering 20,000 items.
It would be interesting to know how the select2 JS would perform with such a long list...
But if it is already loaded to the DOM i guess it would be ok ( might take a few seconds to react though )
Please let me know how it performing if you implement the solution.

Adding content with hooks

I have a beginner question: I want to add a product search form to a WordPress theme via a hook. I want to wrap the product search in a div in order to be able to style it. How can I add the div to the following:
add_action('after_main', my_custom_function');
my_custom_funtion() {
get_product_search_form;
}
Thanks for your help.
It's pretty simple:
add_action('after_main', 'my_custom_function');
function my_custom_function() {
echo '<div class="product-search">' . get_product_search_form( FALSE ) . '</div>';
}
Then, anywhere there is a do_action( 'after_main' ) in your code, this will echo out the search form wrapped in the div. You can change the class, I just added that for the example.
Edit: passed FALSE to the function. get_product_search_form() echoes by default. Passing FALSE returns it instead.
Second edit: You can also use the filter get_product_search_form like this:
add_filter( 'get_product_search_form', function( $form ) {
return '<div class="product-search">' . $form . '</div>';
});

Edit default read more text in WordPress

I would like to customize the read-more link on my WordPress theme, however I would like it to be able to get the attributes sent in the read more tag.
So the <--more--> tag would return the default
While <--more Some Attribute --> would return Some Attribute.
I'm aware that I can edit the read more text with what's below. I just can't figure out how to get the attributes or vars that are passed to the more short-code. If I could figure this out I could simply check if it exists and if not then place in the default text.
function modify_read_more_link() {
return '<div class="read-more"><a class="more-link button" href="' . get_permalink() . '">Custom Read More Link Text</a></div>';
}
what customization you are trying to do ? what about changing the class or using that class use jquery and customize the div !!!
WordPress makes this technique easy, and customizable.
https://codex.wordpress.org/Customizing_the_Read_More
I found the answer to my problem.
Inside my function.php file I needed
function wrap_readmore($more_link) {
//Check if link contains default (more...), if it does replace with Read More
if (preg_match('(more…)', $more_link)) {
$more_link = str_replace('(more…)', 'Read More', $more_link);
}
return '<div class="small-12 columns text-center">' . $more_link . '</div>';
}
add_filter('the_content_more_link', 'wrap_readmore');

how to add pages dropdown for custom post type in reading settings

I would like to add a dropdown of pages for each of my custom post types in the reading settings just under dropdown for posts.
The dropdown of pages for my custom post type is used to configure the archive url by associating to existing page.
As wordpress suggest in https://codex.wordpress.org/Settings_API, I would add a new field like this:
function eg_settings_api_init() {
add_settings_section(
'eg_setting_section',
'Example settings section in reading',
'eg_setting_section_callback_function',
'reading'
);
add_settings_field(
'eg_setting_name',
'Example setting Name',
'eg_setting_callback_function',
'reading',
'eg_setting_section'
);
register_setting( 'reading', 'eg_setting_name' );
}
add_action( 'admin_init', 'eg_settings_api_init' );
function eg_setting_section_callback_function() {
echo '<p>Intro text for our settings section</p>';
}
function eg_setting_callback_function() {
echo '<input name="eg_setting_name" id="eg_setting_name" type="checkbox" value="1" class="code" ' . checked( 1, get_option( 'eg_setting_name' ), false ) . ' /> Explanation text';
}
But the problem is that I dont know how to position this so it is displayed directly underneath the posts dropdown.
There is no way to add your code in between the Default settings because these settings comes from file /wp-admin/options-reading.php as a whole page and there is not add_action's to add your custom section between them.
The option left is to do changes in core files but it not advisable.
You can only use jQuery to move your section wherever want.

Wordpress custom metabox checkbox to display text on front page

I'm creating a video site in wordpress that will feauture both videoes and live streaming. The live streaming is occational and I'm trying to add a checkbox in the "new post" section where the user can check the box to display an alert that they are streaming live on the front page.
This is my code so far, but it does not save that the chebox is checked.
function register_post_assets(){
add_meta_box('live-tv', __('Live TV'), 'add_featured_meta_box', 'post', 'advanced', 'high');
}
add_action('admin_init', 'register_post_assets', 1);
function add_featured_meta_box($post){
$featured = get_post_meta($post->ID, 'live-tv', true);
echo "<label for='live-tv'>".__('Is this a live broadcast post?', 'foobar')."</label>";
echo "<input type='checkbox' name='live-tv' id='live-tv' value='1' ".checked(1, $featured)." />";
}
function save_featured_meta($post_id){
if (isset($_REQUEST['live-tv']))
update_post_meta(esc_attr($post_id, '_featured-post', esc_attr($_REQUEST['featured-post'])));
}
add_action('save_post', 'save_featured_meta');
I'm also wondering how i can check if the checkbox is checked to display content on the front page. Thank you so much for your time and any help will be appreciated!
You have an error in your save_featured_meta function:
It has to be like this:
function save_featured_meta($post_id)
{
if (isset($_REQUEST['live-tv']))
update_post_meta(esc_attr($post_id), '_featured-post', esc_attr($_REQUEST['featured-post']));
}
You didn't close the esc_attr() at the right place.

Categories