Search code examples
phpwordpresswordpress-themingcustom-post-type

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


I have a custom post called 'project'.

I need to get 'titles' that logged in user wrote.

I tried the following code but it doesn't show any titles.

I'm a beginner... I looked into but I can't find which one has problems.

Would you please correct my code?

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

Thank you.


Solution

  • I would use WP_Query instead, it's cleaner and easier to read. Take look at the following code:

    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 };
    }
    

    Let me know if it's what you're looking for!