Wordpress 如何使用自定义查询来获取登录用户的 post 标题?

Wordpress how to use custom query to get logged in users' post title?

我有一个名为 'project' 的自定义 post。

我需要获取登录用户写的 'titles'。

我尝试了以下代码,但它没有显示任何标题。

我是新手...我查了一下,但找不到哪个有问题。

请您更正我的代码好吗?

function output_projects_list() {
  global $wpdb;

  $custom_post_type = 'project'; // define your custom post type slug here
  $current_user = get_userdata(get_current_user_id());
  $current_user_name = $current_user->display_name;

  // A sql query to return all the logged in users' post titles 
$results = $wpdb->get_results( $wpdb->prepare( "
SELECT ID
   , post_title 
FROM {$wpdb->posts} 
WHERE post_type = %s
 , author = %s"
 , and post_status = 'publish'
", $custom_post_type, $current_user_name ), ARRAY_A );

  // Return null if we found no results
  if ( ! $results )
      return;

  foreach( $results as $index => $post ) {
    $output = $post['post_title'];
  }
  return $output;
}
    
echo output_projects_list();

谢谢。

我会改用 WP_Query,它更清晰易读。看看下面的代码:

function user_published_posts()
{
  $query = new WP_Query(array(
    "author"        => get_current_user_id(),
    "post_type"     => "project",
    "post_status"   => "publish"
  ));

  while ($query->have_posts()) {
    $query->the_post(); ?>
    <a href="<?php the_permalink(); ?>">
      <h3><?php the_title(); ?></h3>
    </a>
    <span><?php the_author() ?></span>
<?php };
}

让我知道这是否是您要找的!