dousi4257 2019-05-02 10:26
浏览 50
已采纳

如何在Wordpress函数中简化此代码?

I'm Trying to make a function, my code works but i wonder is there any way to simplify my code? with loop maybe?

Background:

I try to show data from usermeta (the usermeta from plugin) so these are the meta key:

  • child_name
  • child_name_1
  • child_name_2
  • child_name_3

and so on.. based on how much user input their children in database.

example, if user only input 2 children, meta key will be:

  • child_name
  • child_name_1

temporary, i limit only 3 children to input, because i can't simplify it.

function get_child_name(){

$user = wp_get_current_user();
$count_extra_field = $user->wppb_repeater_field_15_extra_groups_count;
$count_child = $count_extra_field + 1;


$child_name_0 = $user->child_name;
$child_name_1 = $user->child_name_1;
$child_name_2 = $user->child_name_2;

$child_names = array($child_name_0,$child_name_1,$child_name_2);

$n=0;
foreach($child_names as $child_name) {
if($n==$count_child) break;
$n++;
echo $child_name;
}
}
add_shortcode('child_names', 'get_child_name');

Above code is works, as I use it now. but is it possible to simplify it / automate the process? So, user can input as many children as possible. or if I want to increase the limit (for input children names) I don't have to add the code again manually, is it possible?

  • 写回答

1条回答 默认 最新

  • dongting3135 2019-05-03 08:46
    关注

    I have tried to simplify the code. Meta fields are being created dynamically based on index. Please check code below. With this you dont have to touch this function again when you want to increase the number of fields.

    function get_child_name(){
    
        $user = wp_get_current_user();
    
        $count_extra_field = $user->wppb_repeater_field_15_extra_groups_count;
    
        $names = array();
    
        for ( $i = 0; $i < $count_extra_field; $i++ ) {
            $meta_key = 'child_name';
            $key_suffix = ( 0 === $i ) ? '' : '_' . $i ;
            $meta_key .= $key_suffix;
    
            if ( $user->$meta_key ) {
                $names[] = $user->$meta_key;
            }
        }
    
        if ( ! empty( $names ) ) {
            foreach ( $names as $name ) {
                echo $name;
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误