我在Wordpress中有一个函数,可以获取字段并返回一个字符串。该函数在当前帖子上调用时工作正常,但现在我需要让该函数在当前帖子之外运行并从其他帖子中获取数据。我正在尝试:
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'post'
));
if($posts) {
foreach( $posts as $post ) {
$postid = $post->ID;
$datafrompost[] = custom_func($postid);
}
echo print_r($datafrompost);
}
如何让函数运行不同的帖子?
下面是它将获取的函数类型的示例:
//[inactivesubjects]
function inactivesubjects_func( $atts ){
$inactivesubjects = get_field('inactive_subjects');
return $inactivesubjects;
}
add_shortcode( 'inactivesubjects', 'inactivesubjects_func' );
此函数工作正常,并在当前帖子中运行时获取inactive_subjects内容。
////////////////////////////更新///////////////////////////
因此,按照 Hobo 的建议,我会将其添加到函数中:
//[inactivesubjects]
function inactivesubjects_func( $anact ){
$inactivesubjects = get_field('inactive_subjects', $anact);
return $inactivesubjects;
}
add_shortcode( 'inactivesubjects', 'inactivesubjects_func' );
而这个到电话
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'post'
));
if($posts) {
foreach( $posts as $post ) {
$datafrompost[] = inactivesubjects_func($anact);
}
echo print_r($datafrompost);
}
但它没有指定帖子?
///
真正让我困惑的是这会起作用
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'post'
));
if($posts) {
foreach( $posts as $post ) {
$string = get_field('inactive_subjects', $post->ID);
}
echo print_r($string);
}
为什么我不能在 foreach 中使用 inactivesubjects_func()?(请注意,inactivesubjects_func()是一个示例,我尝试在其他帖子上运行的实际函数相当大)
你没有遵循我所说的 - 你改变的比我说的要多(也许评论太短,让我无法清楚地解释)。 根据您的第一次编辑,这应该有效。
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'post'
));
if($posts) {
foreach( $posts as $post ) {
$datafrompost[] = inactivesubjects_func($post->ID);
}
echo print_r($datafrompost);
}
function inactivesubjects_func( $anact){
$inactivesubjects = get_field('inactive_subjects', $anact);
return $inactivesubjects;
}
如果你想使用inactivesubjects_func
作为短代码,你会有一个问题,因为WordPress传递短代码参数的方式,但这是一个单独的问题。