• 跳至主要导航
  • Skip to main content
  • 跳到主要侧边栏

WP站点

2665

原始创世纪教程和5000多个保证代码

片段

  • 支持
  • 通讯
  • 影片
  • 登录

高级会员? -请求自定义代码

前言

The 前言 construct only works with arrays.

这意味着您必须 使用数组 像这样: 数组( '1', '2', '3' );

Or functions which return an array like get_categories.

前言 用于遍历数组中的每个键/值对:

$key = array( '1', '2', '3' );

foreach( $key as $value ) 

print $value;

如果将上述代码包装在打开和关闭php标签中,并将其放入文件中,它将输出123。

那’是对数组使用foreach的最基本示例。

这里’有几个将foreach与键/值对数组以及返回数组的函数一起使用的几个常用示例。

将以下函数添加到您的子主题函数文件中,以查看每个代码段在前端输出的内容。

范例1: 将数组与foreach循环一起使用

下面的示例打印数组中每个键的值:

add_action( 'loop_start', 'for_each_example_1' );

function for_each_example_1() {

$key = array( 'Number 1', 'Number 2', 'Number 3' );

foreach( $key as $value ) 

echo $value;
    
}

范例2: 在foreach中使用数组

A different way to code ( array ) when using 前言 :

add_action( 'genesis_entry_header', 'for_each_example_2' );

function for_each_example_2() {

$key = ( 'note 1, note 2, note 3' );

foreach( ( array ) $key as $value ) 

echo $value;

}

例子3: 与功能一起使用foreach。

This example uses the get_categories function which returns an array of categories.

add_action( 'genesis_entry_footer', 'for_each_example_3' );

function for_each_example_3() {

$key = get_categories();

foreach( $key as $value ) 

echo $value->name;

}

例子4: 使用foreach的变量的常用名称

通常,你’ll find the name of 变数 与foreach一起使用’t be named $key and $value but more descriptive like $categories as $category or $tags as $tag as seen in the following example:

add_action( 'genesis_after_entry', 'for_each_example_4' );

function for_each_example_4() {

$categories = get_categories();

foreach( $categories as $category ) 

echo $category->name;

}

示例 与get_tags,get_categories和get_terms一起使用foreach

相关教程

  • 前言循环中的创世纪列类
  • 从图片网址获取附件ID

PHP函数

读者互动

发表评论 取消回复

你一定是 登录 to post a comment.

主侧边栏

PHP代码

template_include

get_body_class

如果别的

数组

class_exists

前言

冲刺

add_action

打印

变量

广告 · WPEngine · 创世记 · 登录

  • 高级会员的工作方式
  • 报名
  • 支持
  • 订阅详细信息/发票
  • 标记教程
  • 访问下载问题

        1. <noscript class="rhkUzOT"><mark id="rer8PFI"></mark></noscript>

          1. <audio id="NZnMwmo" class="NBMCeOJ"><span class="h0QPGnk"></span></audio>