php - 如何从 Woocommerce 中的数组中检索链接产品 URL?
问题描述
我在 Woocommerce 管理部分的“追加销售”下添加了一个新的自定义链接产品字段。
我使用了以下代码(归功于 TheYaXxE):
// Display the custom fields in the "Linked Products" section
add_action( 'woocommerce_product_options_related', 'woocom_linked_products_data_custom_field' );
// Save to custom fields
add_action( 'woocommerce_process_product_meta', 'woocom_linked_products_data_custom_field_save' );
// Function to generate the custom fields
function woocom_linked_products_data_custom_field() {
global $woocommerce, $post;
?>
<p class="form-field">
<label for="upsizing_products"><?php _e( 'Upsizing Product', 'woocommerce' ); ?></label>
<select class="wc-product-search" multiple="multiple" style="width: 50%;" id="upsizing_products" name="upsizing_products[]" data-placeholder="<?php esc_attr_e( 'Search for a product…', 'woocommerce' ); ?>" data-action="woocommerce_json_search_products_and_variations" data-exclude="<?php echo intval( $post->ID ); ?>">
<?php
$product_ids = get_post_meta( $post->ID, '_upsizing_products_ids', true );
foreach ( $product_ids as $product_id ) {
$product = wc_get_product( $product_id );
if ( is_object( $product ) ) {
echo '<option value="' . esc_attr( $product_id ) . '"' . selected( true, true, false ) . '>' . wp_kses_post( $product->get_formatted_name() ) . '</option>';
}
}
?>
</select> <?php echo wc_help_tip( __( 'Select Products Here.', 'woocommerce' ) ); ?>
</p>
<?php
}
// Function the save the custom fields
function woocom_linked_products_data_custom_field_save( $post_id ){
$product_field_type = $_POST['upsizing_products'];
update_post_meta( $post_id, '_upsizing_products_ids', $product_field_type );
}
好消息,一切正常!
但是,现在我正在尝试在产品页面上显示选定的链接产品供客户查看。我只想显示网址。我的问题是,我怎样才能只检索所选产品的 URL?
我使用了以下行,但它总是会返回一个空数组:
$custom_field_url = get_post_meta( $product->get_id(), '_bigger_size_url', true );
还尝试了以下方法,但它检索到的是当前产品而不是链接的产品:
$custom_field_url = get_permalink( $product->get_id(), '_bigger_size_url', true );
解决方案
据我了解,您需要产品的 URL 并且您有 ID。
由于 WooCommerce 产品在 WordPress 中是“自定义帖子类型”,因此您可以使用get_permalink()函数获取 URL,如下所示:
$product_url = get_permalink( $product->get_id() );
推荐阅读
- javascript - 如何替换 jquery 地图中的数据并在后面添加逗号
- r - 如何根据分组 data.frame 中另一列中的 any() 填充列?
- python - 如何绘制 TensorBoard 图?
- javascript - javascript如何找到包含文本的DOM节点?
- javascript - Jquery 问题创建闪烁的文本和图像
- drupal - Drupal 8.x + GraphQL 模块自定义类型/字段插件接收错误“字段必须是字段名称作为键的对象”
- python - OpenCV 操作会阻碍 NumPy 算术吗?
- wordpress - 奇怪的代码被注入到 WordPress 网站中,除非在登录时
- excel - VBA 中的透明图标
- curl - 无法通过负载均衡器传递查询 IP