0

I'm attempting to override the URL of the 'Buy Product' button for all External/Affiliate WooCommerce products. The button needs to link to a contact page and pre-fill the 'Subject' form field with the product title included via query string (e.g. Product enquiry: Product Title).

After reading https://stackoverflow.com/a/43947253/4068853 I've been able to get pretty close by adding the following to functions.php:

// Override external button url
function override_external_product_url( $url, $product ){
    if ( 'external' === $product->get_type() ) {
        // custom add to cart url example
        $url = home_url( "/contact/?your-subject=Product enquiry:");
    }
    return $url;
}
add_filter( 'woocommerce_product_add_to_cart_url', 'override_external_product_url', 10, 2 );

The only thing remaining is to add the product title to the end of the query string. I know the product title can be fetched with <?php the_title_attribute(); ?> but being a PHP noob I'm just not sure how to implement this into the function?

Thanks.

2
  • <? php the_title_attribute(); ?> is a wrong syntax. You have to append the php directly to the <? like this : <?php the_title_attribute(); ?>
    – Cid
    Commented Jun 26, 2018 at 9:50
  • Thanks, my bad - corrected now.
    – peterjrees
    Commented Jun 26, 2018 at 9:53

1 Answer 1

0

Ended up using get_the_title instead because the_title_attribute was causing an error (product title text duplicating and rendering outside the button markup). Also added url encoding, final code looks like:

// Override external button url
function override_external_product_url( $url, $product ){
    if ( 'external' === $product->get_type() ) {
        // custom add to cart url example
        $url = home_url("/contact/?your-subject=" . urlencode("Product Enquiry: " . get_the_title()));
    }
    return $url;
}
add_filter( 'woocommerce_product_add_to_cart_url', 'override_external_product_url', 10, 2 );

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.