I’m building my first WordPress plugin and i’m having a little bit of trouble achieving the functionality I would like.
Essentially what I’m trying to do is save a dynamic array to options.php
I’ll try and explain the functionality in a bit more depth. Basically, the user will select a post_type
from a dropdown of all the available post_types including custom post types. Using jQuery, I’m detecting state changes on that dropdown to then post to a function in the plugin which will output all the available field_types
associated with the selected post_type as labels and checkboxes.
https://www.dropbox.com/s/zacpvq85c5u9lrq/Screen%20Shot%202015-12-21%20at%2012.01.12.png?dl=0
https://www.dropbox.com/s/txyigfe81k0wd1i/Screen%20Shot%202015-12-21%20at%2012.01.23.png?dl=0
I can determine which checkboxes have been checked and create a javascript array of them, how do I then get this array, to wordpress and then have it saved as a preconfigured setting_field
?
What I’ve got so far.
I output all the current post_types as part of a select input.
<select name="comparison_pt" id="comparison_pt" value="<?php echo get_option('comparison_pt'); ?>" value="<?php echo get_option('comparison_pt'); ?>">
<?php
$types = get_post_types(array());
$fields = get_fields();
foreach($types as $type) { ?>
<option value='<?php echo $type; ?>'><?php echo $type; ?></option>
<?php } ?>
</select>
Based on the selected option from the above dropdown
$('#settings_post_type').change(function() {
var selected_post_type = $('#settings_post_type option:selected').text();
$.ajax({
url: plugin_object.admin_url,
type: 'POST',
data: {
action: 'get_settings_field_values',
type: selected_post_type
},
success: function(response) {
console.log('AJAX POST => SUCCESS');
$('#settings_field_types').text('');
$('#settings_field_types').append(response);
},
error: function(response) {
console.log('AJAX POST => ERROR');
console.log(response);
}
});
});
I use the selected value as a WP_Query post_type parameter, returning only 1 post and using that to determine the available field_types for that post.
This outputs a number of labels and checkboxes as can be seen in the images provided, when they’re clicked I have a function to detect which checkboxes are checked and then pushes them into an array e.g. var selected = ['population', 'growth_pa'];
I want to save this array in wordpress as an settings_field which is already predefined.
add_settings_field("comparison_ft", "Comparison Field Types", "display_fields_form_element", "plugin-options", "options_section");