为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
一只萌萌小番薯 2022-01-02 15:35:09
我想让一个简码显示一个值,它是 Wordpress 中的自定义字段。在这种情况下,变量“prijs”。我已经在网上尝试了很多解决方案,但到目前为止还没有运气。谁能帮我 ?为什么这个脚本不显示任何东西?如何显示自定义字段“prijs”?<?phpfunction showdetails_shortcode( $attr, $content = null ) {    return <?php $key="prijs"; echo get_post_meta($post->ID, $key, true); ?>}add_shortcode('showdetails', 'showdetails_shortcode');?>
查看完整描述

1 回答

?
慕容708150

TA贡献1831条经验 获得超4个赞

为什么这个脚本不显示任何内容?


提供的代码显示了几个语法错误,其中最关键的是<?php在 PHP 语句中重新调用。


如果prijs是放置此短代码的帖子的良好自定义字段键,则它应该可以工作。


function showdetails_shortcode( ) {


   $post_id = get_the_ID();


//either output the value or let us know the code is working but the value has not been found

   $output = get_post_meta( $post_id, 'prijs', true) ? get_post_meta( $post_id, 'prijs', true) : 'NO CUSTOM VALUE FOUND' ;


   return $output;


}


add_shortcode('showdetails', 'showdetails_shortcode');

回应评论,这是一个带有两个字段和表格输出的版本,请记住,会有更清晰(更灵活和简洁)的方法来导出变量并为更多字段生成输出。


function showdetails_shortcode( ) {


   $post_id = get_the_ID();


   //extract the field values

   $field1 = get_post_meta( $post_id, 'prijs', true) ? get_post_meta( $post_id, 'prijs', true) : 'PRIJS NOT FOUND';

   $field2 = get_post_meta( $post_id, 'prijs2', true) ? get_post_meta( $post_id, 'prijs2', true) : 'PRIJS2 NOT FOUND';


   //prepare html table output

   $output = '<table><tbody>'; 

   $output .= '<tr><td>' . $field1 . '</td></tr>';

   $output .= '<tr><td>' . $field2 . '</td></tr>'; 

   $output .= '</tbody></table>';


   //return the html    

   return $output;


}


add_shortcode('showdetails', 'showdetails_shortcode');


查看完整回答
反对 回复 2022-01-02
  • 1 回答
  • 0 关注
  • 148 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号