对于woocommerce,我希望将$gclid变量的值合并到下面的href="%s"中。我通过将$gclid放在$product->add_to_cart_url()后面来编辑它,但这不起作用。

global $product;
$gclid=$_GET['gclid']; //Read gclid and store it in $gclid

echo apply_filters(
    'woocommerce_loop_add_to_cart_link',
    sprintf(
         '<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>',
         esc_url( $product->add_to_cart_url().$gclid ),
         esc_attr( isset( $quantity ) ? $quantity : 1 ),
         esc_attr( $product->id ),
         esc_attr( $product->get_sku() ),
         esc_attr( isset( $class ) ? $class : 'button' ),
         esc_html( $product->add_to_cart_text() )
    ),
    $product
);

我做错什么了?
谢谢。

最佳答案

你的问题有点不清楚
您应该首先指定您想要编辑loop/add-to-cart.phpwoomerce模板,该模板在shop和archives woomerce页面上显示add to cart按钮。
当它在href<a>标记中设置get url时,例如:

http://www.myshop.com/shop/?add-to-cart=208

要使其工作,您需要添加以下内容:
http://www.myshop.com/shop/?add-to-cart=208&gclid=601

这将工作添加&+gclid=+的值gclid(这里例如601)…
因此,下面的代码将完美工作(请参见this test server上的实际操作):
<?php
/**
 * Loop Add to Cart
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/loop/add-to-cart.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see         https://docs.woocommerce.com/document/template-structure/
 * @author      WooThemes
 * @package     WooCommerce/Templates
 * @version     2.5.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

global $product;

// Just for testing (replace after with $gclid=$_GET['gclid'];)
$gclid = '&gclid=120';
// $gclid=$_GET['gclid'];

echo apply_filters( 'woocommerce_loop_add_to_cart_link',
    sprintf( '<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>',
        esc_url( $product->add_to_cart_url().$gclid ),
        esc_attr( isset( $quantity ) ? $quantity : 1 ),
        esc_attr( $product->id ),
        esc_attr( $product->get_sku() ),
        esc_attr( isset( $class ) ? $class : 'button' ),
        esc_html( $product->add_to_cart_text() )
    ),
$product );

// Checking that you get 'gclid' value (just for test)
// (will display normally the 'gclid' value after the button add-to-cart)
echo '<p>gclid value: '. $_GET['gclid'] .</p>;

问题当然来自于您的$gclid=$_GET['gclid'];。你必须确保你得到了'gclid'的值。
一旦你确定你得到了'gclid'值,你就应该稍微改变一下,这样:
 $gclid= '&gclid=' . $_GET['gclid'];

这应该管用…

10-04 12:59