将WP循环分解为函数

时间:2015-11-27 10:25:49

标签: php wordpress loops

我正在尝试将一个简单的foreach循环分解为两个函数:start和end。

functions.php

function days_start() {
  $days = [];
  $meals_monday = get_field('monday_meal');
  $meals_tuesday = get_field('tuesday_meal');
  $meals_wednesday = get_field('wednesday_meal');
  $meals_thursday = get_field('thursday_meal');
  $meals_friday = get_field('friday_meal');
  $meals_saturday = get_field('saturday_meal');
  $meals_sunday = get_field('sunday_meal');
  array_push($days, $meals_monday, $meals_tuesday, $meals_wednesday, $meals_thursday, $meals_friday, $meals_saturday, $meals_sunday);

  foreach( $days as $day ):
}

function days_end() {
  endforeach;
}

我这样做,所以我可以多次使用它而无需重写它。但是,我收到了这个错误:

"syntax error, unexpected '}'"

我想我一定是个盲人,但我不明白为什么会出现这种情况。或者是否无法在函数内部使用foreach函数而不关闭它?

谢谢!

1 个答案:

答案 0 :(得分:0)

好的,我从函数中删除了foreach语句并执行了此操作:

的functions.php

function days_before_loop() {
  global $days;

  $days = [];
  $meals_monday = get_field('monday_meal');
  $meals_tuesday = get_field('tuesday_meal');
  $meals_wednesday = get_field('wednesday_meal');
  $meals_thursday = get_field('thursday_meal');
  $meals_friday = get_field('friday_meal');
  $meals_saturday = get_field('saturday_meal');
  $meals_sunday = get_field('sunday_meal');
  array_push($days, $meals_monday, $meals_tuesday, $meals_wednesday, $meals_thursday, $meals_friday, $meals_saturday, $meals_sunday);

  return $days;
}

然后这样称呼:

days_before_loop();
foreach( $days as $day ):
  // do some stuff
endforeach();

谢谢!