woocommerce offtopic - Product related to post by title

admin2025-06-02  1

How to insert to single post related woocommerce product with the same title?

Best would be something like WC shortcode

[add_to_cart id="XX"]

but like this

[add_to_cart title="XXXXXXXXX"]

How to insert to single post related woocommerce product with the same title?

Best would be something like WC shortcode

[add_to_cart id="XX"]

but like this

[add_to_cart title="XXXXXXXXX"]
Share Improve this question edited Mar 18, 2019 at 14:10 codesnipper asked Mar 18, 2019 at 14:02 codesnippercodesnipper 34 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

default woocommerce shortcodes won't do that. you'll need to write something custom to get the product by title, grab the ID from there, and then call the add to cart shortcode using the ID. something like this:

add_shortcode('add_to_cart_by_title', 'add_to_cart_by_title');
function add_to_cart_by_title ($atts) {
    if (!class_exists('WooCommerce')) {
        return '';
    }
    $args = shortcode_atts(array(
        'title' => ''
    ), $atts);

    $related_product = get_page_by_title($args['title'], OBJECT, 'product');

    if ($related_product) {
        $product_id = $related_product->ID;
        return do_shortcode('[add_to_cart id="' . $product_id . '"]');
    }
    return '';
}

which you would then call like [add_to_cart_by_title title="whatever"]

You could also remove the title attribute from the shortcode call and have it just get the title of the current post via get_the_title()

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748796504a313793.html

最新回复(0)