如何在帖子中为WooCommerce区块的外部产品添加目标空白属性



我想将Products by Tag块添加到帖子中。有些是外部产品,那么我如何将目标空白添加到按钮中以打开新窗口?默认情况下,所有外部链接都会重定向。我还想更改它的按钮文本。我使用了以下代码片段,但它不起作用。

function wp_target_blank( $link ) {
global $product;
if ( $product->is_type( 'external' ) ) {
$link = sprintf( '<a href="%s" data-quantity="%s" class="%s" data-product_id="%s" data-product_sku="%s" aria-label="%s" rel="nofollow" target="_blank">%s</a>',
esc_url( $product->add_to_cart_url() ),
esc_attr( isset( $quantity ) ? $quantity : 1 ),
esc_attr( isset( $class ) ? $class : 'wp-block-button__link add_to_cart_button' ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
esc_html( $product->add_to_cart_text() ),
esc_html( $product->add_to_cart_text() )
);
}
return $link;
}

请让我知道怎么做。非常感谢。

原始Wooccommerce源代码:

protected function render_product( $product ) {
$data = (object) array(
'permalink' => esc_url( $product->get_permalink() ),
'image'     => $this->get_image_html( $product ),
'title'     => $this->get_title_html( $product ),
'rating'    => $this->get_rating_html( $product ),
'price'     => $this->get_price_html( $product ),
'badge'     => $this->get_sale_badge_html( $product ),
'button'    => $this->get_button_html( $product ),
);

return apply_filters(
'woocommerce_blocks_product_grid_item_html',
"<li class="wc-block-grid__product">
<a href="{$data->permalink}" class="wc-block-grid__product-link">
{$data->image}
{$data->title}
</a>
{$data->badge}
{$data->price}
{$data->rating}
{$data->button}
</li>",
$data,
$product
);
}

要将目标空白添加到外部产品:

/**
* @snippet       Add target blank to external products
* @author        Vinay jain
* @compatible    WooCommerce 5
*/

add_filter( 'woocommerce_blocks_product_grid_item_html', 'add_target_blank_to_externl_products', 9999, 3 );

function add_target_blank_to_externl_products( $html, $data, $product ) {
$target = '';
if( $product->is_type( 'external' ) ) {
$target = 'target="_blank"';
}
return "<li class="wc-block-grid__product">
<a {$target} href="{$data->permalink}" class="wc-block-grid__product-link">
{$data->image}
{$data->title} //change button text here
</a>
{$data->badge}
{$data->price}
{$data->rating}
{$data->button}
</li>";
}

最新更新