Gravity Forms:根据文章分类显示字段及获取分类合并标签问题
解决方案:Gravity Forms 获取嵌入文章分类并控制字段显示
Gravity Forms 默认的 {embed_post} 系列合并标签不包含文章分类的直接支持,你可以通过以下两种方式实现需求:
方案一:自定义文章分类合并标签
通过代码注册自定义合并标签,之后就能像使用 {embed_post:post_title} 一样调用文章分类信息。将以下代码添加到主题的 functions.php 文件(建议使用子主题,避免主题更新丢失代码)或自定义插件中:
// 注册自定义合并标签 add_filter( 'gform_merge_tags', 'add_post_category_merge_tag', 10, 4 ); function add_post_category_merge_tag( $merge_tags, $form_id, $fields, $element_id ) { $merge_tags[] = array( 'label' => '嵌入文章的分类名称', 'tag' => '{embed_post:category}', 'group' => '文章' ); return $merge_tags; } // 替换合并标签内容 add_filter( 'gform_replace_merge_tags', 'replace_post_category_merge_tag', 10, 7 ); function replace_post_category_merge_tag( $text, $form, $entry, $url_encode, $esc_html, $nl2br, $format ) { if ( strpos( $text, '{embed_post:category}' ) === false ) { return $text; } // 获取当前嵌入的文章ID $post_id = isset( $_GET['gf_post_id'] ) ? intval( $_GET['gf_post_id'] ) : get_the_ID(); if ( !$post_id ) { return str_replace( '{embed_post:category}', '', $text ); } // 获取文章的第一个分类名称(可根据需求调整为分类ID/slug) $categories = get_the_category( $post_id ); $category_content = $categories ? $categories[0]->name : ''; // 如果需要分类ID,替换为 $categories[0]->term_id;需要slug替换为 $categories[0]->slug return str_replace( '{embed_post:category}', $category_content, $text ); }
添加完成后,你就可以在表单的字段设置或通知内容中使用 {embed_post:category} 获取当前嵌入文章的分类信息。
方案二:直接根据分类动态控制字段显示
如果你的需求是根据文章分类自动显示/隐藏特定表单字段,可以使用 gform_pre_render 钩子实现,无需依赖合并标签:
add_action( 'gform_pre_render', 'control_field_display_by_category' ); function control_field_display_by_category( $form ) { // 获取当前嵌入的文章ID $post_id = isset( $_GET['gf_post_id'] ) ? intval( $_GET['gf_post_id'] ) : get_the_ID(); if ( !$post_id ) { return $form; } // 获取文章的分类slug列表 $categories = get_the_category( $post_id ); $category_slugs = wp_list_pluck( $categories, 'slug' ); // 配置目标字段和分类:替换为你的实际字段ID和分类slug $target_field_id = 3; // 要控制显示的字段ID $required_category = 'tech'; // 匹配的分类slug // 遍历表单字段,设置显示状态 foreach ( $form['fields'] as &$field ) { if ( $field->id == $target_field_id ) { // 文章属于目标分类则显示字段,否则隐藏 $field->isHidden = !in_array( $required_category, $category_slugs ); } } return $form; }
修改代码中的 $target_field_id 和 $required_category 为你的实际信息,表单加载时会自动根据当前文章的分类状态控制字段显示。
注意事项
- 如果使用自定义文章类型和自定义分类法,需要将
get_the_category替换为get_the_terms( $post_id, '你的自定义分类法slug' )。 - 修改主题代码前建议备份文件,避免操作失误导致网站故障。
内容的提问来源于stack exchange,提问作者Brad
相关产品推荐
相关产品推荐

