【问题标题】:Wordpress store get_posts data in variablesWordpress 将 get_posts 数据存储在变量中
【发布时间】:2017-05-03 11:06:15
【问题描述】:

我有这个代码

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();

在此先感谢,感谢您提供的任何帮助。

【问题讨论】:

    标签: php arrays wordpress variables


    【解决方案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++;
    }; 
    

    【讨论】:

    • 如何访问第一篇文章的标题? ^^
    【解决方案2】:

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

    $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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多