如何将functions.php中的$cert_url传递到WordPress自定义页面使用
解决方法
第一步:修改functions.php中的逻辑,将生成的证书链接持久化存储
你当前写的get_cert_url函数仅在触发woocommerce_thankyou钩子时返回链接,没有做存储,其他页面自然无法直接调用这个变量。只需要在生成$cert_url后将它存入订单自定义字段即可:
add_action( 'woocommerce_thankyou', 'get_cert_url' ); function get_cert_url( $order_id ) { global $wpdb; $msf_campaign_status = array('wc-completed'); $msf_campaign_detail = get_post_meta($order_id); $msf_campaign_fund = $msf_campaign_detail['msf_charity_fund'][0]; $order = wc_get_order( $order_id ); if( $order->has_status('processing') ){ $name_on_e_cert = str_replace(" ", "+", $msf_campaign_detail['name_on_e_cert'][0]); $msf_charity_name = get_option('wc_fields_billing'); if($msf_campaign_detail['charity_organizations'][0] == 'msf_charity_1'){ $charity_name = $msf_charity_name['charity_organizations']['options']['msf_charity_1']; } elseif ($msf_campaign_detail['charity_organizations'][0] == 'msf_charity_2') { $charity_name = $msf_charity_name['charity_organizations']['options']['msf_charity_2']; } elseif ($msf_campaign_detail['charity_organizations'][0] == 'msf_charity_3') { $charity_name = $msf_charity_name['charity_organizations']['options']['msf_charity_3']; } elseif ($msf_campaign_detail['charity_organizations'][0] == 'msf_charity_4') { $charity_name = $msf_charity_name['charity_organizations']['options']['msf_charity_4']; } $donateto = str_replace(" ", "+", $charity_name); $subtotal = $order->get_subtotal(); $amount = (($subtotal*25)/100); $request = wp_remote_retrieve_body(wp_remote_get('https://www.api_website.com.my/api/c/product.ashx?key=api_key&orderid='.$order_id.'&name='.$name_on_e_cert.'&donateto='.$donateto.'&amount='.$amount.'')); $data = json_decode($request); $result[]= $data; foreach($result[0] as $line) { $cert_url = $line; } // 新增:将生成的证书链接存入订单自定义字段 update_post_meta($order_id, 'generated_cert_url', $cert_url); return $cert_url; } }
第二步:自定义页面中调用存储的证书链接
首先你需要在自定义页面中先获取对应订单的ID(如果是 WooCommerce 感谢页的自定义模板,可以直接拿到全局的$order_id变量;如果是用户中心的订单详情页,也可以从当前查询参数中获取订单ID),再调用get_post_meta读取之前存的链接即可:
// 先获取对应订单ID,以下为示例,请根据你的页面实际场景调整获取方式 $order_id = get_query_var('order-received'); // 读取证书链接 $cert_url = get_post_meta($order_id, 'generated_cert_url', true); // 链接存在才渲染分享按钮 if($cert_url): ?> <a href="https://www.facebook.com/sharer?u=<?php echo urlencode($cert_url); ?>&t=Digital-Certificate" target="_blank" rel="noopener noreferrer">Share this on Facebook</a> <?php endif; ?>
注意事项
- 输出链接到Facebook分享参数时记得用
urlencode()转义,避免特殊字符导致链接失效 - 如果你的自定义页面和订单没有直接关联,可以考虑把链接存在用户的元数据中,或者通过URL参数传递订单ID来获取对应链接
内容的提问来源于stack exchange,提问作者Boon
相关产品推荐
相关产品推荐

