With Woocommerce, is it possible to pass the previous page title to a custom checkout fields?
Advertisement
Answer
Updated – The following code example uses PHP Session to grab the previous page title (this code example can be extended):
JavaScript
x
add_action( 'template_redirect', 'grab_previous_page_title' );
function grab_previous_page_title() {
session_start();
// Not on checkout page
if( ! is_checkout() ) {
$_SESSION['previous_page_title'] = wp_title('', false);
}
}
In checkout page you will be able to get the previous page title using:
JavaScript$previous_page_title = $_SESSION['previous_page_title'];
Then in checkout page we can add this previous page title in a hidden input field:
JavaScript
// Checkout: Display a hidden input field with previous page title inside checkout form
add_action( 'woocommerce_after_order_notes', 'hidden_input_field_previous_page_title' );
function hidden_input_field_previous_page_title() {
if( isset($_SESSION['previous_product_title']) ) {
echo '<input type="hidden" name="previous_page_title" value="'.$_SESSION['previous_page_title'].'">';
}
}
Then when order is submitted, we save the custom hidden field value as order meta data:
JavaScript
// Save the custom hidden field value as order meta data
add_action('woocommerce_checkout_create_order', 'save_previous_page_title', 22, 2 );
function save_previous_page_title( $order, $data ) {
if ( isset($_POST['previous_page_title']) ) {
$order->update_meta_data( '_previous_page_title', sanitize_text_field($_POST['previous_page_title']) );
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.