I have a shortcode in use at present that embeds a button on selected product pages. Upon clicking this button, the user is brought to a contact form on another page and the title of the Product from where the button was clicked is appended to the end of the contact form URL as a query string. This product title is then gleaned from the query string and auto-filled into a field labeled “products” on the contact form.

Code as follows:

add_shortcode( 'dynamic_contact_button', 'button_product_page' );

function button_product_page() {
global $product;
return "href="https://wordpress.stackexchange.com/contact-form/?products=Product:%20" .$product->get_title(). "&#contact_form"";
}

This creates a URL such as:

https://www.example.com/contact-form/?products=Product: Brown Paint - 1L&#contact_form

It works quite well… until a product title includes an “unsafe” character which can’t be appended to the query string. For example, the apostrophe character to denote measurement in feet in a product title – the query string gets cut where one of these appear meaning only part of the product title is carried over to the form. I’m sure there are many other unsafe characters which would cause similar issues.

Is there a something I can add to the code here to encode the Product title text being appended… so space becomes %20, an apostrophe becomes %27, etc. I see there is an urlencode option in PHP but my understanding is lacking on how I might implement it

2 s
2

To encode the URL, you could use the PHP urlencode( $url ) function or use the WordPress urlencode_deep( $array | $str ); function.

add_shortcode( 'dynamic_contact_button',    'button_product_page' );

function button_product_page() {
    global $product;
    return urlencode( "https://wordpress.stackexchange.com/contact-form/?products=Product:%20" .$product->get_title(). "&#contact_form" );
}

links:

WordPress – urlencode_deep

urlencode

Leave a Reply

Your email address will not be published. Required fields are marked *