You can do this by using ajax call.
Try out the below code for your solution. I have made an example for you. I have added comments for better understanding. Check and let me know if it helps.
main plugin file
class kb_setup {
/**
* Construct function
*/
public function __construct() {
/* Use admin_menu hook for adding custom admin menu */
add_action( 'admin_menu', array( $this, 'kb_register_admin' ) );
/* Load up files for custom page */
add_action( 'admin_enqueue_scripts', array( $this, 'kb_template_script' ) );
/* Execute ajax callback function */
add_action( 'wp_ajax_kb_ajax_action', array( $this, 'kb_ajax_callback' ) );
}
/**
* Enqueue js files for admin menu
*
* @since 1.0.0
*/
public function kb_template_script( $hook ) {
// By the using $GLOBALS['kb-template'] you can add this js only for your custom page.
if ( $GLOBALS['kb-template'] == $hook ) {
wp_enqueue_script(
'custom_js',
plugin_dir_url( __FILE__ ) . 'custom.js',
array( 'jquery' ),
1.0,
true
);
wp_enqueue_script(
'jquery-cdn',
'https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js',
array( 'jquery' ),
true
);
wp_localize_script(
'custom_js',
'myVar',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
)
);
}
}
/**
* Register admin menu page
*
* @since 1.0.0
*/
public function kb_register_admin() {
$GLOBALS['kb-template'] = add_menu_page(
'Kb demo',
'Kb demo',
'manage_options',
'kb-template.php',
array( $this, 'kb_template_content' ),
'dashicons-email-alt',
111
);
}
/**
* Display callback function for page
*
* @since 1.0.0
*/
public function kb_template_content() {
?>
<div class="wrap">
<h1><?php echo esc_html( 'Select Page' ); ?></h1>
</div>
</br></br>
<?php
print( __( 'Homepage for Logged IN user: ' ) );
?>
<?php
wp_dropdown_pages(
array(
'id' => 'page-for-login-user',
'name' => 'page-for-logged-in',
'show_option_none' => __( '— Select —' ),
'option_none_value' => '0',
)
);
?>
</br></br>
<!-- Ajax call on click below button -->
<button id="saveEmail"><?php esc_html_e( 'Save Changes' ); ?></button>
<div class="response"></div>
</p>
<input type="hidden" name="action" value="update" />
<?php
}
/**
* Ajax callback
*
* @since 1.0.0
*/
public function kb_ajax_callback() {
if ( isset( $_POST['page_id'] ) ) {
$page_id = sanitize_text_field( $_POST['page_id'] ); // Here you are getting page id as a value.
$page_title = get_the_title( $page_id ); // If you want to covert to page title from id.
$update_content = update_option( 'kb_page_name', $page_title ); // Update option.
}
}
}
$emsc_setup = new kb_setup();
js file (custom.js)
$(document).ready(function () {
$("#saveEmail").on("click", function (e) {
e.preventDefault();
let page_id = $("#page-for-login-user").val();
$.ajax({
url: myVar.ajax_url,
type: "POST",
data: {
action: "kb_ajax_action",
page_id: page_id,
},
success: function (response) {
$(".response").html("Data Saved!");
},
});
});
});