Wordpress将get_posts数据存储在变量中

时间:2017-05-03 11:06:15

标签: php arrays wordpress variables

我有这个代码

global $post;
    $size = array(75,75);
    $args = array( 'numberposts' => 3, 'category' => 'Allgemein' );
    $myposts = get_posts( $args );



    foreach( $myposts as $post ) {  setup_postdata($post); 

        echo the_title();
        echo "<br>";
        echo the_excerpt();
        echo "<br>";
        echo the_permalink(); 
        echo "<br>";
        echo get_the_post_thumbnail($post_id, $size);
        echo "<br>";


     };  

如何在不同的变量中保存每个帖子的数据?:

 $post9_title = $latesposts[8]->the_title();

提前致谢,感谢您提供的任何帮助。

2 个答案:

答案 0 :(得分:1)

为数组中的每个帖子设置计数器和拉值。

$posts_info = array();
$counter = 0;

foreach( $myposts as $post ) {  setup_postdata($post); 

    $posts_info[$counter]['title'] = get_the_title($post->ID);
    $posts_info[$counter]['excerpt'] = get_the_excerpt($post->ID);
    $posts_info[$counter]['link'] = get_the_permalink($post->ID);
    $posts_info[$counter]['thumb'] = get_the_post_thumbnail($post->ID, $size);

    $counter++;
}; 

答案 1 :(得分:0)

将它们存储在一个数组中,以便您可以广泛使用它。

$store_post_data = array();
foreach( $myposts as $post ) {  setup_postdata($post); 
        $store_post_data[get_the_ID()]['title'] = get_the_title();
        $store_post_data[get_the_ID()]['excerpt'] = get_the_excerpt();
        $store_post_data[get_the_ID()]['permalink'] = get_permalink();
        $store_post_data[get_the_ID()]['thumbnail'] = get_the_post_thumbnail($post->ID, $size);
};  

然后在循环外打印数组。

print_r($store_post_data);