Issue with querying

时间:2021-01-20 作者:Andrew Giardina

我的WordPress查询有问题。我根本不是最好的程序员,我通常只是通过到处学习和根据需要编辑/编写代码来获得。周一晚上,我几乎整晚都在做一些事情,我似乎有一个问题需要重新审视。我很确定问题出在meta\\u值上,但我还是没有足够的经验来克服这一点。如有任何帮助/建议,将不胜感激。

下面的代码正确地提取了装运帖子,但无论我搜索的meta\\u值是多少,它都会提取所有帖子。

    $posts = get_posts(array(
        \'numberposts\' => -1,
        \'post_type\' => \'shipments\',
        \'meta_key\' => \'customer_user_id\',
        \'meta_value\' => $user->ID
    ));
    
    if($posts)
    {
        echo \'<ul>\';
    
        foreach($posts as $post)
        {
        echo "My code here";
}
}

1 个回复
SO网友:LWS-Mo

正如我所说的,您的代码似乎还可以,但我认为您没有事先获得当前用户
类似这样的方法有效:

$user = wp_get_current_user(); // get current user, to get the ID

$posts = get_posts(array(
    \'numberposts\' => -1,
    \'post_type\' => \'shipments\',
    \'meta_key\' => \'customer_user_id\',
    \'meta_value\' => $user->ID 
));

if( $posts ){
    echo \'<ul class="shipment-posts-list">\';

    foreach( $posts as $post ){

        // get post data
        $post_id = $post->ID; //current post ID
        $post_title = $post->post_title; // current post title
        $post_thumbnail = get_the_post_thumbnail( $post_id ); // current post thumbnail

        // get post metadata
        $shipment_tracking = get_post_meta($post_id, \'tracking_number\', true);
        $customer_user_id = get_post_meta($post_id, \'customer_user_id\', true);

        echo \'<li class="shipment-\'.$post_id.\'">\';

            // example:

            echo \'<h3>\'.$post_title.\'</h4>\'; // show post title

            echo $post_thumbnail; // show post thumbnail

            echo $customer_user_id; // show customer user id

        echo \'</li>\';

    }

    echo \'</ul>\';
}
同样,在编辑问题之前,您试图以错误的方式获取元数据。

获取元数据,如:

$shipment_tracking = get_post_meta($post_id, \'tracking_number\', true);
请注意$post_id 部分(而不仅仅是$post 就像你一样)。

相关推荐