Skip to content

Instantly share code, notes, and snippets.

@WPprodigy
Created March 26, 2018 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WPprodigy/9b0a4797a178cfb68bb019f1e03e9e42 to your computer and use it in GitHub Desktop.
Save WPprodigy/9b0a4797a178cfb68bb019f1e03e9e42 to your computer and use it in GitHub Desktop.
Make external product's button on archives link to the product page.
add_filter( 'woocommerce_loop_add_to_cart_link', 'wc_ninja_change_external_product_button', 15, 3 );
function wc_ninja_change_external_product_button( $button, $product, $args ) {
$url = $product->add_to_cart_url();
if ( 'external' === $product->get_type() ) {
$url = $product->get_permalink();
}
return sprintf( '<a href="%s" data-quantity="%s" class="%s" %s>%s</a>',
esc_url( $url ),
esc_attr( isset( $args['quantity'] ) ? $args['quantity'] : 1 ),
esc_attr( isset( $args['class'] ) ? $args['class'] : 'button' ),
isset( $args['attributes'] ) ? wc_implode_html_attributes( $args['attributes'] ) : '',
esc_html( $product->add_to_cart_text() )
);
}
@WPprodigy
Copy link
Author

WPprodigy commented Mar 27, 2018

If you wanted to change the button text as well, could do something like this:

add_filter( 'woocommerce_loop_add_to_cart_link', 'wc_ninja_change_external_product_button', 15, 3 );
function wc_ninja_change_external_product_button( $button, $product, $args ) {
	$button_url  = $product->add_to_cart_url();
	$button_text = $product->add_to_cart_text();

	if ( 'external' === $product->get_type() ) {
		$button_url  = $product->get_permalink();
		$button_text = 'View Product Page';
	}

	return sprintf( '<a href="%s" data-quantity="%s" class="%s" %s>%s</a>',
		esc_url( $button_url ),
		esc_attr( isset( $args['quantity'] ) ? $args['quantity'] : 1 ),
		esc_attr( isset( $args['class'] ) ? $args['class'] : 'button' ),
		isset( $args['attributes'] ) ? wc_implode_html_attributes( $args['attributes'] ) : '',
		esc_html( $button_text )
	);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment