0

I want to display categories posts in the following format on the front home:

Health: 1st post 2nd post 3rd post

Fitness: 1st post 2nd post 3rd post

Beauty 1st post 2nd post 3rd post

Example site: beautyhealthtips.in

Does anybody help me?

Thanks!

0
function add_excluded_post_ids( $exclude_post_ids, $posts ) {
    foreach( $posts as $post ) {
        array_push( $exclude_post_ids, $post->ID );
    }
    return $exclude_post_ids;
}

$exclude_post_ids = array();

$latest_posts = get_posts( array(
    'numberposts' => 3
) );
$exclude_post_ids = add_excluded_post_ids( $exclude_post_ids, $latest_posts );

$health_posts = get_posts( array(
    'numberposts' => 3,
    'category' => get_category_by_slug( 'health' )->term_id, // Change accordingly
    'exclude' => $exclude_post_ids
) );
$exclude_post_ids = add_excluded_post_ids( $exclude_post_ids, $latest_posts );

$fitness_posts = get_posts( array(
    'numberposts' => 3,
    'category' => get_category_by_slug( 'fitness' )->term_id, // Change accordingly
    'exclude' => $exclude_post_ids
) );
$exclude_post_ids = add_excluded_post_ids( $exclude_post_ids, $fitness_posts );

$beauty_posts = get_posts( array(
    'numberposts' => 3,
    'category' => get_category_by_slug( 'beauty' )->term_id, // Change accordingly
    'exclude' => $exclude_post_ids
) );

Now you have $latest_posts, $health_posts, $fitness_posts and $beauty_posts. Each one of them stores a set of 3 posts which you can use to generate your HTML. You can use a shortcode that outputs the whole HTML, then insert this shortcode within a "Page" and finally set your homepage to that "Static page".

Note $health_posts, $fitness_posts and $beauty_posts will store the latest posts that belong to those categories, respectively. If you wish to retrieve those posts by another parameter, like amount of views, or randomly, you'll have to use WP_Query instead of get_posts().

  • Thanks, @eduardo-escobar But this code is showing an error while saving in functions.php file - syntax error, unexpected ''exclude'' (T_CONSTANT_ENCAPSED_STRING), expecting ')' – rudyards Oct 21 '18 at 7:41
  • Syntax error, i just fixed it. – Eduardo Escobar Oct 21 '18 at 18:39
  • Ok added successfully. Can you please tell what will be the shortcode?. Some categories have - hyphen like health-care, what will be the code for that $health_care_posts or something else? – rudyards Oct 23 '18 at 6:12
  • @rudyards you need to investigate a little mate, i'd say half the job is done with that code. – Eduardo Escobar Oct 23 '18 at 12:52
  • Ok Thanks but nothing happened with after adding that code in function file. – rudyards Oct 24 '18 at 5:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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