使用foreach循环返回可用字符串或数组时出现问题


Trouble returning usable string or array with foreach loop

我正试图返回一个可以在函数中使用的字符串(在WordPress中通过程序添加术语)。

我的生成字符串的函数基本上是通过匹配特定条件的html元标记进行循环,如下所示:

function getYouTubeTags( $post_id ) {
    $video_id = get_post_meta( get_the_ID(), 'rfvi_video_id', true );
    $tag_url = "http://www.youtube.com/watch?v=" . $video_id;
    $sites_html = file_get_contents($tag_url);
    $html = new DOMDocument();
    @$html->loadHTML($sites_html);
    $meta_og_tag = null;
    foreach( $html->getElementsByTagName('meta') as $meta ) {
        if( $meta->getAttribute('property')==='og:video:tag' ){
            $meta_og_tag = $meta->getAttribute('content');
            print_r ($meta_og_tag . ",");
        }
    }
}

当我简单地执行这个(getYouTubeTags();)时,它返回字符串:

supra vs lambo,tt lambo,twin turbo,street race,texas streets,underground racing,supra,turbo supra,1200hp,nitrous,superleggera,gallardo,

在我为帖子添加术语的功能中,以下内容不起作用:

function rct_save_post_terms( $post_id ) {
    $terms = getYouTubeTags();
    wp_set_post_terms( $post_id, $terms, 'post_tag', true );
}

如果我手动添加第一个函数输出的字符串,它确实有效:

function rct_save_post_terms( $post_id ) {
    $terms = 'supra vs lambo,tt lambo,twin turbo,street race,texas streets,underground racing,supra,turbo supra,1200hp,nitrous,superleggera,gallardo,';
    wp_set_post_terms( $post_id, $terms, 'post_tag', true );
}

此外,根据WordPress的说法,wp_set_post_terms:中的$terms可以是一个数组或逗号分隔的字符串

我知道我一定错过了一些简单的东西,但似乎无法弄清楚。提前感谢您的帮助!

既然你想让这些字符串被重用,为什么不返回这些:

function getYouTubeTags( $post_id ) {
    $out = null;
    $video_id = get_post_meta( get_the_ID(), 'rfvi_video_id', true );
    $tag_url = "http://www.youtube.com/watch?v=" . $video_id;
    $sites_html = file_get_contents($tag_url);
    $html = new DOMDocument();
    @$html->loadHTML($sites_html);
    $meta_og_tag = null;
    foreach( $html->getElementsByTagName('meta') as $meta ) {
        if( $meta->getAttribute('property')==='og:video:tag' ){
            // i seriously doubt this checking i think this should be
            // if($meta->getAttribute('property') == 'og:video') {
            $meta_og_tag = $meta->getAttribute('content');
            // print_r ($meta_og_tag . ",");
            $out[] = $meta_og_tag; // gather them inside first
        }
    }
    return implode(',', $out); // return implode comma delimited strings
}

然后,实际上,你可以使用它们:

function rct_save_post_terms( $post_id ) {
    $terms = getYouTubeTags(); // strings are in here
    wp_set_post_terms( $post_id, $terms, 'post_tag', true );
}

您的原始函数中似乎没有返回值。您需要使用;

return $meta_og_tag;

在函数末尾,将值返回给指定的变量。

此外,您需要使用.=将字符串附加到返回变量的末尾;

$meta_og_tag .= $meta->getAttribute('content');

OR您可以将每个属性保存在一个数组中,并将implode保存为返回值;

// inside loop
$meta_og_tag[] = $meta->getAttribute('content');
// outside loop
return implode(', ',$meta_og_tag);

print_r将简单地回显变量的内容,而不是返回值。

希望这能有所帮助。