Skip to content

Instantly share code, notes, and snippets.

@helgatheviking
Created August 12, 2020 16:48
Show Gist options
  • Save helgatheviking/af72435b3cf729886b852c61c0f2d38c to your computer and use it in GitHub Desktop.
Save helgatheviking/af72435b3cf729886b852c61c0f2d38c to your computer and use it in GitHub Desktop.
Fix add to cart URL/text for external products that don't have an external URL
<?php
/**
* Plugin Name: Mix and Match external product parents
* Plugin URI: https://gist.github.com/helgatheviking/af72435b3cf729886b852c61c0f2d38c
* Description: Fix add to cart URL/text for external products that don't have an external URL. Like when using a product table to group products together.
* Version: 1.0.0
* Author: Kathy Darling
* Author URI: https://kathyisawesome.com
* Text Domain: mnm-external-parent
* Domain Path: /i18n/languages/
* Requires at least: 5.2
* Requires PHP: 7.0
*
* @package WooCommerce
*/
defined( 'ABSPATH' ) || exit;
/**
* Set a flag on external products that do not have an external link.
*/
function kia_set_external_pseudo_parent() {
global $product;
$product->is_parent_container = $product->is_type( 'external' ) && '' === $product->get_product_url() ? true : false;
}
add_action( 'woocommerce_before_shop_loop_item', 'kia_set_external_pseudo_parent' );
/**
* Link to product page for external products with no product URL
*
* @param str $url
* @param obj WC_Product_Mix_and_Match $product
* @return string
*/
function kia_external_product_add_to_cart_url( $url, $product ) {
if ( ! is_product() && $product->is_parent_container ) {
$url = $product->get_permalink();
}
return $url;
}
add_filter( 'woocommerce_product_add_to_cart_url', 'kia_external_product_add_to_cart_url', 10, 2 );
/**
* Link to product page for external products with no product URL
*
* @param str $text
* @param obj WC_Product_Mix_and_Match $product
* @return string
*/
function kia_external_product_add_to_cart_text( $text, $product ) {
if ( $product->is_parent_container ) {
$text = $product->get_button_text() ? $product->get_button_text() : __( 'Select options', 'your-textdomain' );
}
return $text;
}
add_filter( 'woocommerce_product_add_to_cart_text', 'kia_external_product_add_to_cart_text', 10, 2 );
/**
* Link to product page for external products with no product URL
*
* @param str $description
* @param obj WC_Product_Mix_and_Match $product
* @return string
*/
function kia_external_product_add_to_cart_description( $description, $product ) {
if ( $product->is_parent_container ) {
$description = $product->get_button_text() ? $product->get_button_text() : sprintf( __( 'Select options for %s', 'your-textdomain' ), $product->get_name() );
}
return $description;
}
add_filter( 'woocommerce_product_add_to_cart_description', 'kia_external_product_add_to_cart_description', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment