$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>woocommerce offtopic - Product related to post by title|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

woocommerce offtopic - Product related to post by title

matteradmin8PV0评论

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()

Post a comment

comment list (0)

  1. No comments so far