php - 如何将自定义按钮添加到 WooCommerce 产品档案
问题描述
我想在产品档案中添加一个自定义按钮(“查看全部”) 。我已经在单个产品页面上显示了这个自定义按钮。
我想要的是从单个产品页面中删除它并将其添加到 WooCommerce 产品档案中。
已编辑: 此代码还有另一个问题。当我从后端删除链接并使该字段为空然后单击更新按钮时。链接仍然存在。意味着如果我用另一个链接替换它可以正常工作,但是一旦填充了某些内容,该字段就不会变空。如果我用空字段保存产品,页面加载后之前的值仍然存在。
以下是相关代码:
// This function gets the value for the the custom fields from the database and adds it to the frontend output function
function wpse_add_custom_link_output() {
$external_link = get_post_meta(get_the_ID(), '_custom_product_text_field', true);
$html = '<a href="'.$external_link.'" class="custom-button-class" target="_blank" title="'.__('External product link','woocommerce').'">SEE ALL</a>';
echo $html;
};
add_action( 'woocommerce_after_add_to_cart_button', 'wpse_add_custom_link_output', 10, 0 );
// This function creates the field in the backend
function wpse_add_custom_link_field(){
global $woocommerce, $post;
echo '<div class="product_custom_field">';
// Custom Product Text Field
woocommerce_wp_text_input(
array(
'id' => '_custom_product_text_field',
'placeholder' => __('Paste product link here', 'woocommerce'),
'label' => __('Custom product link', 'woocommerce'),
'desc_tip' => 'true'
)
);
echo '</div>';
}
add_action('woocommerce_product_options_general_product_data', 'wpse_add_custom_link_field');
// this function saves the link/text field
function wpse_save_custom_link_field($post_id){
// Custom Product Text Field
$woocommerce_custom_product_text_field = $_POST['_custom_product_text_field'];
if (!empty($woocommerce_custom_product_text_field))
update_post_meta($post_id, '_custom_product_text_field',
esc_attr($woocommerce_custom_product_text_field));
}
add_action('woocommerce_process_product_meta', 'wpse_save_custom_link_field');
解决方案
要在循环存档而不是单个产品页面上使用此自定义按钮,只需在代码中替换以下行:
add_action( 'woocommerce_after_add_to_cart_button', 'wpse_add_custom_link_output', 10, 0 );
以下代码行:
add_action( 'woocommerce_after_shop_loop_item', 'wpse_add_custom_link_output', 20 );
它应该工作。
推荐阅读
- python - unreal.EditorStaticMeshLibrary 中没有 get_lod_build_settings()。(UE4 Python)
- qt - Qt 样式表不适用于树莓派中的第一个选项卡 QTabBar
- android - 无法使用 Fragment 启动活动 compenetInfo
- php - 如何更改 WordPress 文章网格中的阅读更多文本
- asp.net-mvc - Azure Function App 不属于逻辑应用设计器
- r - 带有闪亮的朴素贝叶斯
- java - 在 java swing 面板中放置按钮的布局
- html - How to create grid inside a bootstrap 3 modal
- javascript - 如何使用 Perfume.js 测量小部件/组件的性能
- ruby-on-rails - 在浏览器中输出 URL / 视图 - 来自 Rails .html.erb