有关更多详细信息,请参阅有关使用WordPress自定义字段的初学者指南。
由于自定义字段会向帖子添加元数据,因此可以在WordPress循环中轻松显示它们以及其他帖子内容。但是,有时您可能希望在循环外显示它们。例如,在侧边栏小部件中。这就是它变得有点棘手的时候。
话虽如此,让我们看看如何在WordPress中轻松显示循环外的自定义字段。
|
1
2
3
4
五
6 |
<?phpglobal $wp_query;$postid = $wp_query->post->ID;echo get_post_meta($postid, 'Your-Custom-Field', true);wp_reset_query();?> |
get_post_meta()函数来获取和输出自定义字段数据。
不要忘记使用您的实际自定义字段更改Your-Custom-Field。
您可以自定义代码以满足您的需求。您还可以使用其他查询参数来获取和显示不同帖子和页面的自定义字段数据。
我们来看看另一个例子。这个使用WP_Query类,这是一种更好,更灵活的方式在WordPress主题文件中使用多个循环。
只需将此代码添加到您想要显示自定义字段的主题或子主题中。
|
1
2
3
4
五
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 |
$args = array ( // Post or Page ID'p' => 231,);// The Query$the_query = new WP_Query( $args );// The Loopif ( $the_query->have_posts() ) { while ( $the_query->have_posts() ) { $the_query->the_post(); echo get_post_meta( get_the_ID(), 'Mood', true); } /* Restore original Post Data */ wp_reset_postdata();} else {echo 'Nothing found'; } |
目前为止就这样了。
我们希望本文能帮助您学习如何在WordPress中显示循环外的自定义字段。您可能还希望为初学者看到我们的WordPress主题备忘单。