I am trying to get post title by sql. My sql code is

$query ="SELECT     wp_posts.post_title AS title , 
                    wp_posts.post_content AS content,
                    wp_posts.post_date AS blogdate 
        FROM wp_posts
        WHERE wp_posts.post_status="publish"
        ORDER BY wp_posts.post_date DESC ";
global $wpdb;
$result= $wpdb->get_results($query);


 if ($result){

    foreach($result as $post){
    ?><li><a href="https://wordpress.stackexchange.com/questions/257892/<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
    <?php echo $post->title; ?></a></li><?php
    }
 }else{
     echo "Sorry, No Post Found.";
 }

    die();

Now the problem is I am getting title but the_permalink() is not working.

2 Answers
2

I am not sure why you are using a custom query and not get_posts() or WP_Query as you should.

Anyway, you need to get the post ID …

$query ="SELECT     wp_posts.post_title AS title , 
                    wp_posts.post_content AS content,
                    wp_posts.post_date AS blogdate ,
                    wp_posts.ID AS ID

And then just pass this ID to get_permalink():

get_permalink( $post->ID );

Similar for the title attribute:

the_title_attribute( [ 'post' => $post->ID ] );

Leave a Reply

Your email address will not be published. Required fields are marked *