admin管理员组文章数量:1292698
I am trying to match tag names with form titles to fetch the correct form into the current post, to subscribe to new posts tagged with the current posts tag. I only have 1 tag assigned per post.
The code for categories works well, and I tried to transcribe it for tags, but I am afraid there are syntax errors in the code, because it does not work.
How do I write the correct code?
add_shortcode( 'subscribe-to-tag', function() {
global $wpdb, $post;
$the_tag = get_the_tags( $post->ID );
$tag_name = $the_tag[0]->tag_name;
$id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM wptq_forms WHERE name = '{$tag_name}';"));
if (is_null($id)) { return ''; }
return do_shortcode( '[newsletter_form id="' . intval( $id ) . '"]' );
} );
I am trying to match tag names with form titles to fetch the correct form into the current post, to subscribe to new posts tagged with the current posts tag. I only have 1 tag assigned per post.
The code for categories works well, and I tried to transcribe it for tags, but I am afraid there are syntax errors in the code, because it does not work.
How do I write the correct code?
add_shortcode( 'subscribe-to-tag', function() {
global $wpdb, $post;
$the_tag = get_the_tags( $post->ID );
$tag_name = $the_tag[0]->tag_name;
$id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM wptq_forms WHERE name = '{$tag_name}';"));
if (is_null($id)) { return ''; }
return do_shortcode( '[newsletter_form id="' . intval( $id ) . '"]' );
} );
Share
Improve this question
asked May 10, 2021 at 22:14
Adam AllemanAdam Alleman
133 bronze badges
5
|
1 Answer
Reset to default 1I don't see PHP syntax errors (like unwanted brackets) in your code, but there are two WordPress-specific issues that need to be fixed:
Note that
wpdb::prepare()
needs one or more placeholders (e.g.%s
for strings and%d
for numbers) and the replacement value for each placeholder.So in your case, the correct
$wpdb->prepare()
would be:$wpdb->prepare( "SELECT ID FROM wptq_forms WHERE name = %s", $tag_name );
get_the_tags()
returns an array of term objects on successful requests, and each object is aWP_Term
instance which does not have atag_name
property, onlyname
.Therefore
$the_tag[0]->tag_name
should instead be$the_tag[0]->name
.
本文标签: mysqlMatch tag names with form titles
版权声明:本文标题:mysql - Match tag names with form titles 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741563765a2385601.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
$tag_name = $the_tag[0]->name;
– anton Commented May 10, 2021 at 22:28wptq_forms
table? – Tom J Nowell ♦ Commented May 10, 2021 at 23:19