【问题标题】:Wordpress get the data and push into arrayWordpress 获取数据并推入数组
【发布时间】:2012-09-07 15:36:23
【问题描述】:

我想从 WordPress DB 中获取数据,将它们推送到数组中并将数据传递给 JS。

除了将数据推入foreach ($posts as $post) 中的数组外,一切正常。

完整方法:

        $array = array(); 
        $category_name = "locations";
        $args = array(
            'numberposts' => -1,
            'category_name' => $category_name
        );

        $posts = get_posts($args);      
        foreach ($posts as $post){
            array_push( $array, array(

                "title" => the_title($post->ID),
                "cnt" => the_content($post->ID),
                "id" => the_ID($post->ID),
                "link" => the_permalink($post->ID)

            )); 
        }

当我做print_r($array) 时,我得到以下组合:

Post 39http://localhost:8080/testing/post-3/Post 27http://localhost:8080/testing/post-2/Post 15http://localhost:8080/testing/post-1/Array
(
    [0] => Array
        (
            [title] => 
            [cnt] => 
            [id] => 
            [link] => 
        )

    [1] => Array
        (
            [title] => 
            [cnt] => 
            [id] => 
            [link] => 
        )

    [2] => Array
        (
            [title] => 
            [cnt] => 
            [id] => 
            [link] => 
        )

)


发生了什么事?为什么数据没有正确放入数组中? 任何建议都非常感谢。

【问题讨论】:

    标签: foreach wordpress


    【解决方案1】:

    这些模板标签需要将其 echo 变量设置为 false 才能在该上下文中工作。他们也不将帖子 ID 作为变量,如果设置了 postdata,他们会假定当前帖子。试试:

    the_title('','',false)
    

    https://codex.wordpress.org/Function_Reference/the_title


    -~ -~ -~ -~ -~ -~ -~ -~ 澄清编辑 -~ -~ -~ -~ -~ -~ -~ -~

    这个问题最简洁的解决方案实际上是直接寻址 wp $post 对象。所以对于标题字符串$post->post_title 和内容$post->post_content

    $post 对象中可用的字段在此处列出:

    http://codex.wordpress.org/Function_Reference/get_post#Return

    【讨论】:

    • the_title('','',false) 有效!是否还有其他标准数据(内容、ID、永久链接等)的替代方案?
    • 对于您需要的数据,实际上最好使用get_the_title($postid) 等等,正如 Dan 建议的那样。例如 the_content() 没有 echo false 选项。
    • 刚刚看了一下 get_the_content() ,是的,它也不返回字符串。您最好的选择是将整个帖子作为一个数组获取并从中获取值。使用get_post
    • 大声笑实际上放弃了。由于您已经完成了 get_posts,我认为该帖子已经设置为一个对象。试试$post->post_content,我相信它会给你字符串的内容。使用之前的 get_posts codex 页面链接查看您想要的其他值的名称。
    • $post->post_content 确实有效!谢谢!知道这将如何与自定义元框一起使用吗??
    【解决方案2】:

    这些函数(the_title、the_content 等)不返回值,它们echo 用于输出。他们也不接受 ID 参数。需要使用get_the_titleget_the_content等返回字符串的版本。

    【讨论】:

    • get_the_title 有效。不幸的是 get_the_content 返回空(是的,有一些内容)。任何的想法?谢谢!
    猜你喜欢
    • 2019-03-31
    • 2016-01-13
    • 1970-01-01
    • 2023-03-29
    • 2016-04-10
    • 2014-09-24
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    相关资源
    最近更新 更多