John Davidson

php - Wordpress custom admin page - Save Checkbox

0 comments
Message:


I am trying to create a custom page in the administration panel to save some checkboxes somewhere in an array so that later I can show them in the wordpress theme. But the truth is I am limited, I do not know how to continue to save that information, nor do I know if it is better to use update_option () or update_post_meta () to save that configuration.
I have the following code in the theme's functions file:


function wpdocs_unsub_add_pages() {
add_menu_page(
__( 'Unsub List', 'textdomain' ),
__( 'Unsub Emails','textdomain' ),
'manage_options',
'categoriasrelacionadas',
'wpdocs_unsub_page_callback',
''
);
}

/**
* Display callback for the Unsub page.
*/
function wpdocs_unsub_page_callback() {
echo 'Unsubscribe Email List';
?>

<form method="post"
action="<?php echo esc_html('?page=categoriasrelacionadas'); ?>">

<?php $cat_argtos=array(
'orderby' => 'name',
'order' => 'ASC');

$categorias=get_categories($cat_argtos);
foreach($categorias as $categoria) {
$args=array(
'showposts' => -1,
'category__in' => array($categoria->term_id),
'caller_get_posts'=>1
);
$entradas=get_posts($args);
if ($entradas) {
echo '<p>' .$categoria->name.
'<input type="checkbox"
name="categorias"
value="'.$categoria->term_id.'">
</p>';
}
}
?>
<?php
wp_nonce_field( 'acme-settings-save', 'acme-custom-message' );
submit_button();
?>
</form>
<?php
...
}

What else could I do to save the information and show the selected boxes?



My Answer:
To save the checkbox information in an array and later display it in the WordPress theme, you can use the `update_option()` function to save the configuration. Here's an example of how you can modify your code to save the checkbox information:

php
function wpdocs_unsub_add_pages() {
add_menu_page(
__( 'Unsub List', 'textdomain' ),
__( 'Unsub Emails', 'textdomain' ),
'manage_options',
'categoriasrelacionadas',
'wpdocs_unsub_page_callback',
''
);
}

function wpdocs_unsub_page_callback() {
if (isset($_POST['checkbox_value'])) {
$checkbox_value = $_POST['checkbox_value'];
update_option('checkbox_option', $checkbox_value);
}

$saved_checkbox_value = get_option('checkbox_option');

echo '
';
echo '';
echo '';
echo '
';
}


In this code snippet, we added a form in the `wpdocs_unsub_page_callback()` function to display a checkbox. When the form is submitted, the checkbox value is saved using the `update_option()` function. Later, you can retrieve the saved checkbox value using the `get_option()` function.

Make sure to replace `'checkbox_option'` with a unique option name for your checkbox configuration. You can then use the saved checkbox value in your theme to display the checkboxes as needed.

Rate this post

4 of 5 based on 7907 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us