0

in my index.php page, i used this code but its not showing description ie: 100 characters of my articles? Don't recommend replacing get_the_content() with $post->post_content, i know that works. but need correct output keeping get_the_content().let me know what other thing should i change in this code to get the output.

<?php
$args = array('posts_per_page'=>3,
    'orderby'=>'rand',
    'post_type'=>'post'
);

$post_data = get_posts($args);

foreach($post_data as $post){

    echo '<a href="'.get_the_permalink().'">'.get_the_title().'</a><br>';

    $post_data = substr(strip_tags(get_the_content()),0,100).'...';
    echo $post_data."<br>";

}
?>
2
  • What output do you get? substr in the post_content isn't the best approach as it could lead to breaking the word. Commented Nov 2, 2017 at 13:51
  • @Drupalizeme as i said, i am getting everything in output except the 100 characters description.
    – TheDose
    Commented Nov 2, 2017 at 13:54

1 Answer 1

2

Please read about the get_the_permalink and get_the_title. These functions are developed to fetch the details from global $post variable. Your local $post won't be effective here.

You should either pass local $post to these functions like get_the_permalink($post) and get_the_title($post). For get_the_content, you will need to use apply_filters('the_content',$post->post_content);

However, preferred way is to create an object of WP_Query. Please read about its a powerful class to query everything about posts. In your case, it will look something like this

<?php
$args = array('posts_per_page'=>3,
    'orderby'=>'rand',
    'post_type'=>'post'
);

$randomPosts = new WP_Query($args);

while($randomPosts->have_posts()){
    $randomPosts->the_post();

    echo '<a href="'.get_the_permalink().'">'.get_the_title().'</a><br>';

    echo substr(strip_tags(get_the_content()),0,100).'...';
    echo "<br>";

}
?>

I have not tested above code but, I guess, you get the idea.

2
  • get_the_content should work as well, try removing substr and strip_tags if it is returning post contents and there is not issue with the post data.
    – M-R
    Commented Nov 2, 2017 at 14:43
  • thanks man it worked. i just posted 1 more small question. if you could answer that as well. thanks alot.
    – TheDose
    Commented Nov 2, 2017 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.