猿问

如何在短代码中显示自定义字段(变量)

我想让一个简码显示一个值,它是 Wordpress 中的自定义字段。在这种情况下,变量“prijs”。我已经在网上尝试了很多解决方案,但到目前为止还没有运气。谁能帮我 ?为什么这个脚本不显示任何东西?如何显示自定义字段“prijs”?


<?php

function showdetails_shortcode( $attr, $content = null ) {

    return <?php $key="prijs"; echo get_post_meta($post->ID, $key, true); ?>

}

add_shortcode('showdetails', 'showdetails_shortcode');

?>


一只萌萌小番薯
浏览 160回答 1
1回答

慕容708150

为什么这个脚本不显示任何内容?提供的代码显示了几个语法错误,其中最关键的是<?php在 PHP 语句中重新调用。如果prijs是放置此短代码的帖子的良好自定义字段键,则它应该可以工作。function showdetails_shortcode( ) {&nbsp; &nbsp;$post_id = get_the_ID();//either output the value or let us know the code is working but the value has not been found&nbsp; &nbsp;$output = get_post_meta( $post_id, 'prijs', true) ? get_post_meta( $post_id, 'prijs', true) : 'NO CUSTOM VALUE FOUND' ;&nbsp; &nbsp;return $output;}add_shortcode('showdetails', 'showdetails_shortcode');回应评论,这是一个带有两个字段和表格输出的版本,请记住,会有更清晰(更灵活和简洁)的方法来导出变量并为更多字段生成输出。function showdetails_shortcode( ) {&nbsp; &nbsp;$post_id = get_the_ID();&nbsp; &nbsp;//extract the field values&nbsp; &nbsp;$field1 = get_post_meta( $post_id, 'prijs', true) ? get_post_meta( $post_id, 'prijs', true) : 'PRIJS NOT FOUND';&nbsp; &nbsp;$field2 = get_post_meta( $post_id, 'prijs2', true) ? get_post_meta( $post_id, 'prijs2', true) : 'PRIJS2 NOT FOUND';&nbsp; &nbsp;//prepare html table output&nbsp; &nbsp;$output = '<table><tbody>';&nbsp;&nbsp; &nbsp;$output .= '<tr><td>' . $field1 . '</td></tr>';&nbsp; &nbsp;$output .= '<tr><td>' . $field2 . '</td></tr>';&nbsp;&nbsp; &nbsp;$output .= '</tbody></table>';&nbsp; &nbsp;//return the html&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;return $output;}add_shortcode('showdetails', 'showdetails_shortcode');
随时随地看视频慕课网APP
我要回答