How to submit a button automatically after every scheduled hours ? I tried some JavaScript but all failed.
What I am doing?
- I am trying to fetch product categories from an external API
Why I want this to be fetched every scheduled time ?
- so that if someone not clicks manually, then also it will fetch after scheduled time, say any time or after every 8 hours
My codes:
<?php
/*
Add menu page and button to fetch productcategories
*/
function add_productcategories_menu_page()
{
add_menu_page(
'Fetch productcategories',
'Fetch productcategories',
'manage_options',
'productcategories',
'productcategories_menu_page'
);
}
add_action('admin_menu', 'add_productcategories_menu_page');
function productcategories_menu_page()
{
?>
<div class="wrap">
<h1>productcategories</h1>
<form method="post" action="">
<?php wp_nonce_field('fetch_productcategories_nonce', 'fetch_productcategories_nonce'); ?>
<input type="submit" name="fetch_productcategories" value="Fetch productcategories" class="button button-primary">
</form>
</div>
<?php
}
/*
Get product Categories from API
*/
function import_productcategories() {
$url = '';
$response = wp_remote_get( $url );
$data = wp_remote_retrieve_body( $response );
$json = json_decode( $data );
if ( ! empty( $json ) ) {
$existing_productcategories = get_terms( 'productcategories', array( 'hide_empty' => false ) );
foreach ( $existing_productcategories as $existing_productcategorie ) {
$found = false;
foreach ( $json as $category ) {
if ( $category->productCategoryNameFi === $existing_productcategorie->productCategoryNameFi ) {
$found = true;
break;
}
}
if ( ! $found ) {
wp_delete_term( $existing_productcategorie->term_id, 'productcategories' );
}
}
foreach ( $json as $category ) {
$term = term_exists( $category->productCategoryNameFi, 'productcategories' );
if ( $term === 0 || $term === null ) {
wp_insert_term( $category->productCategoryNameFi, 'productcategories', array(
'slug' => sanitize_title( $category->productCategoryNameFi )
) );
}
}
}
}
function fetch_productcategories_handler()
{
if (isset($_POST['fetch_productcategories']) && wp_verify_nonce($_POST['fetch_productcategories_nonce'], 'fetch_productcategories_nonce')) {
import_productcategories();
echo '<div class="updated"><p>productcategories fetched successfully!</p></div>';
}
}
add_action('admin_init', 'fetch_productcategories_handler');
?>
I tried
<script>
setInterval(function() {
document.getElementById('fetch-form').submit();
}, 60000); // Submit the form every 1 minute (60,000 milliseconds)
</script>
and
add_action('wp_loaded', function() {
$interval = 60; // 1 minute
wp_schedule_event(time(), 'minutes', 'fetch_webcategories', array($interval));
});
function fetch_webcategories() {
update_web_categories_terms();
}