I need to initiate an action on a WooCommerce product page if parameters are added to the end of the page. For example:
If this action is initiated, it will sync the product pricing via API from an external source (I know how to do that already) and reload the page.
What I don't know is how to make the plugin that will perform the sync respond to the GET request parameters.
I'm comfortable using the WordPress API if that's the best solution. I've created plugins before, I just haven't dealt with this situation.
Thanks!
I need to initiate an action on a WooCommerce product page if parameters are added to the end of the page. For example:
https://somesite/products/some-random-product?some-parameter=true
If this action is initiated, it will sync the product pricing via API from an external source (I know how to do that already) and reload the page.
What I don't know is how to make the plugin that will perform the sync respond to the GET request parameters.
I'm comfortable using the WordPress API if that's the best solution. I've created plugins before, I just haven't dealt with this situation.
Thanks!
Share Improve this question asked Aug 18, 2019 at 21:53 DifsterDifster 1011 bronze badge1 Answer
Reset to default 0If you want to do the processing and reloading, more or less, user not noticing, you could execute a custom function on template_redirect
action.
function check_parameter() {
if ( isset( $_GET['bar'] ) && 'foo' === $_GET['bar'] && is_singular( 'product' ) ) {
// get remote data e.g. with wp_remote_get( 'http://example' );
// do something
// redirect
global $wp;
wp_redirect( home_url( $wp->request ) ); // this should redirect to the same url without parameters
die;
}
}
add_action( 'template_redirect', 'check_parameter' );
If you want to show the user that something is happening, then you could use admin ajax (or wp rest api). Something like this,
PHP
add_action( 'wp_ajax_my_action', 'my_action_function' );
add_action( 'wp_ajax__nopriv_my_action', 'my_action_function' ); // for non logged in users, if needed
function my_action_function() {
// check nonce
// check for capabilities, if needed
// check for required $_POST parameters / values
// do something
wp_send_json_error( $data );
// or
wp_send_json_success( $data ); // $data could be the new price for example
}
jQuery (use js if you prefer)
jQuery.ajax({
method: 'POST',
url: 'admin-ajax.php', // use wp_localize_script for this
data: {
action: 'my_action',
nonce: 'your-nonce-field-value', // use wp_localize_script for this
bar: 'foo', // use js/jquery to get url parameter(s)
},
success: function(response){
// do something with response.data
},
});