I'm currently working on a plugin that adds a metabox to the post editing area of the dashboard. The metabox has "conditional" fields so I want to show/hide fields based on others, mostly for the user's sake.
I've added a JS file, which works, to add/remove classes for that effect. The JS works fine and so does my CSS.
However, any classes added or removed does not save once I hit the post's "update/publish" button. What step am I missing to ensure that when a post is saved, the state of my JS is saved as well? Do I have to use something like wp_localize_script to pass something between my JS/PHP?
I'm using jQuery since I only need JS for adding/removing classes. I thought Ajax would be overkill in this case, but I'm new to writing JS for a plugin, so open to hearing suggestions about best practices. Thanks in advance! :-)
PS: I'm open to being linked to specific resources if the explanation is too big to write here.
Not sure if this helps, but I'll drop my code in anyway. Here's is the enqueue for my files:
function admin_scripts_styles( $hook ) {
if ( $hook !== 'post.php' ) {
return;
}
//Yes, unfortunately, this is being done in a custom theme, not a plugin, hence get_template_directory_uri
wp_enqueue_script( 'admin-featured-posts-scripts', get_template_directory_uri() . 'inc/admin-js/admin-featured-posts.js', [
'jquery'
] );
wp_enqueue_style( 'admin-featured-posts-scripts', get_template_directory_uri() . 'inc/admin-css/admin-featured-posts.css' );
}
//this gets called in an init() function but adding here for context
add_action( 'admin_enqueue_scripts', [ $this, 'admin_scripts_styles' ] );
And here is my function that adds/removes classes. This isn't my whole JS file, just the function for this question. Yes the file is being enqueued and yes, this is firing correctly. It also works no problem, but just doesn't "save" once I update/publish the post. It fires with an on change event handler.
function enableOptions() {
var enableVal = $(this).attr('value'),
fieldOptions = $('#fieldWrapper');
if (enableVal === 'yes') {
fieldOptions.removeClass('disabled');
} else {
fieldOptions.addClass('disabled');
}
}
Here is what the saving function looks like with a nonce. The saving part works as far as saving field values when the post is published or updated.
public function save_featured_metabox( $post_id ) {
$nonce_action = 'featured_metabox_nonce_action';
$nonce_name = 'featured_metabox_nonce';
$featured_fields = [
0 => 'featured_field_one',
1 => 'featured_field_two',
2 => 'featured_field_three',
3 => 'featured_field_four',
];
if ( ! isset( $_POST[ $nonce_name ] ) || ! wp_verify_nonce( $_POST[ $nonce_name ], $nonce_action ) ) {
return $post_id;
}
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return $post_id;
}
foreach ( $featured_fields as $featured_field ) {
update_post_meta( $post_id, '_' . $featured_field, $this->sanitize_featured_fields( $featured_field ) );
}
}
I've purposely simplified file/class names to post here as an example.