WordPress产品分类(productcat)自定义字段短码调用失败求助
问题:产品分类自定义字段无法通过短码调用
我已将以下代码添加至function.php文件,但无法通过短码调用产品分类(productcat)的自定义字段数据。
已添加的代码:
function productcat_add_form_fields(){ echo '<div class="form-field"> <label for="cct_pdf_url">File PDF Download URL</label> <input name="cct_pdf_url" id="cct_pdf_url" type="text" value=""> <p id="cct_pdf_url-description">A url to a map that shows the neighborhood.</p> </div>'; } function save_productcat_meta($term_id){ if(!isset($_POST['cct_pdf_url'])){ return; } update_term_meta( $term_id, 'cct_pdf_url', sanitize_url( $_POST['cct_pdf_url'] )); } function productcat_edit_form_fields($term) { $url = get_term_meta( $term->term_id, 'cct_pdf_url', true ); echo '<tr class="form-field"> <th scope="row"><label for="up_more_info_url">File PDF Download URL</label></th> <td><input name="cct_pdf_url" id="cct_pdf_url" type="text" value="'.$url.'"> <p class="description">A url to a map that shows the neighborhood.</p></td> </tr>'; } add_action('productcat_add_form_fields', 'productcat_add_form_fields'); add_action('productcat_edit_form_fields', 'productcat_edit_form_fields'); add_action('create_productcat', 'save_productcat_meta'); add_action('edited_productcat', 'save_productcat_meta');
尝试过的短码(均无效):
[wpbb post:cct_pdf_url taxonomy="productcat"][wpbb post:meta_box field='cct_pdf_url'][wpbb archive:productcat key='cct_pdf_url'][wpbb post:custom_field key='cct_pdf_url']
解决方案
原因分析
你使用的WPBakery短码默认聚焦于文章(Post)上下文,而分类术语的元数据属于术语(Term)范畴,现有短码要么上下文不匹配,要么格式不正确,导致无法读取数据。
方案一:自定义专属短码(推荐)
直接编写一个专门用于获取产品分类PDF链接的短码,灵活性更高,不受页面上下文限制。
将以下代码添加到function.php:
function get_productcat_pdf_url_shortcode($atts) { // 设置短码参数默认值 $atts = shortcode_atts(array( 'term_id' => '', // 分类ID 'slug' => '' // 分类别名 ), $atts); $term_id = $atts['term_id']; // 通过别名获取分类ID(如果没传ID但传了别名) if (empty($term_id) && !empty($atts['slug'])) { $term = get_term_by('slug', $atts['slug'], 'productcat'); if ($term && !is_wp_error($term)) { $term_id = $term->term_id; } } // 当前是产品分类存档页时,自动获取当前分类ID if (empty($term_id) && is_tax('productcat')) { $term_id = get_queried_object_id(); } // 获取并返回PDF链接 if (!empty($term_id)) { $pdf_url = get_term_meta($term_id, 'cct_pdf_url', true); if (!empty($pdf_url)) { // 可根据需求修改返回格式,比如纯链接或带样式的按钮 return '<a href="' . esc_url($pdf_url) . '" target="_blank" class="productcat-pdf-btn">下载PDF</a>'; } } // 无数据时返回空 return ''; } add_shortcode('productcat_pdf', 'get_productcat_pdf_url_shortcode');
使用方式:
- 在产品分类存档页直接调用:
[productcat_pdf] - 指定分类ID调用:
[productcat_pdf term_id="123"](替换123为你的分类ID) - 指定分类别名调用:
[productcat_pdf slug="your-category-slug"](替换为你的分类别名)
方案二:修正WPBakery短码格式(仅适用于分类存档页)
如果必须使用WPBakery自带短码,需使用术语元数据专用格式,且仅在产品分类存档页生效:
[wpbb archive:term_meta key='cct_pdf_url' taxonomy='productcat']
额外小修复
你的编辑表单代码里,标签的for属性写错了,应该把<label for="up_more_info_url">改成<label for="cct_pdf_url">,这样点击标签能聚焦到输入框,提升后台操作体验。
内容的提问来源于stack exchange,提问作者AmirZaaba
相关产品推荐
相关产品推荐

