我在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中的内容。
//////////////////////////// UPDATE ////////////////// /////////
所以按照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);
}
但它没有指定帖子?
////////////////////更新2 //////////////////////
真正令我困惑的是这将起作用
$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()是一个例子,我试图在其他帖子上运行的实际功能相当大)
答案 0 :(得分:1)
你不遵循我所说的 - 你改变的次数比我说的要多(或许评论太短,不能让我解释清楚)。根据您的第一次编辑,这应该有效。
$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通过短代码参数的方式,但这是一个单独的问题。