我尝试创建一个代码来更改商店循环上的产品URL。
因此,我创建了以下代码,但它并没有像预期的那样工作。我们的目标是,我们可以为特定产品输入一个自定义URL,然后当客户在商店循环中点击该产品时,它会重定向到该自定义URL。这是我当前的版本:
add_action( 'woocommerce_product_options_advanced', 'woostore_custom_product_link' );
function woostore_custom_product_link() {
global $woocommerce, $post;
echo '<div class="options_group">';
woocommerce_wp_text_input(
array(
'id' => '_custom_url',
'label' => __( 'Custom Page link', 'actions-pro' ),
'placeholder' => 'http://',
'desc_tip' => 'true',
'description' => __( 'Enter the custom product page url for this product to link to from the shop page.', 'actions-pro' )
)
);
echo '</div>';
}
// Save Field
add_action( 'woocommerce_process_product_meta', 'woostore_link_to_custom_product_save' );
function woostore_link_to_custom_product_save( $post_id ) {
if ( ! empty( $_POST['_custom_url'] ) ) {
update_post_meta( $post_id, '_custom_url', esc_attr( $_POST['_custom_url'] ) );
} else {
update_post_meta( $post_id, '_custom_url', esc_attr( $_POST['_custom_url'] ) );
}
}
add_action( 'init', 'woostore_product_change_link' );
function woostore_product_change_link() {
global $post, $product;
if ( get_post_meta( $post->ID, '_custom_url', true ) ) {
remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 );
add_action( 'woocommerce_before_shop_loop_item', 'woostore_template_loop_product_link_open', 1 );
}
}
我没有得到任何错误。但我这边不行。任何建议吗?
关于您的代码尝试的一些评论/建议
- 使用
woocommerce_loop_product_link
过滤器钩子vsinit
,这样你就不必删除/添加钩子 - 要保存字段,您可以使用
woocommerce_admin_process_product_object
钩子,相对于过时的woocommerce_process_product_meta
钩子 - 不需要使用全局变量
得到:
function action_woocommerce_product_options_advanced() {
woocommerce_wp_text_input(
array(
'id' => '_custom_url',
'label' => __( 'Custom Page link', 'actions-pro' ),
'placeholder' => 'http://',
'desc_tip' => 'true',
'description' => __( 'Enter the custom product page url for this product to link to from the shop page.', 'actions-pro' )
)
);
}
add_action( 'woocommerce_product_options_advanced', 'action_woocommerce_product_options_advanced' );
// Save custom field
function action_woocommerce_admin_process_product_object( $product ) {
// Isset
if ( isset( $_POST['_custom_url'] ) ) {
// Update
$product->update_meta_data( '_custom_url', sanitize_url( $_POST['_custom_url'] ) );
}
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 );
// Custom url
function filter_woocommerce_loop_product_link( $the_permalink, $product ) {
// Get meta value
$url = $product->get_meta( '_custom_url' );
// NOT empty
if ( ! empty ( $url ) ) {
$the_permalink = $url;
}
return $the_permalink;
}
add_filter( 'woocommerce_loop_product_link', 'filter_woocommerce_loop_product_link', 10, 2 );