Search code examples
wordpressgridposts

I am trying to create custom field to fetch posts by title and display them in a hero grid n my WP website


I am new to WordPress, and coding in general. I am trying to start a news website. Now, I have created a grid hero section for featured posts. I would like to be able to select which posts are placed in a hero grid.I assume that one of the ways is to fetch them by post_title.I have watched a couple tutorials and tryed to implement that functionality with ACF plugin but with no success. So far I am only able to display posts in a grid but they are not displayed by my personal preference which is what I would like to achieve. Tnx in advnace. Here is the code:

<section class="page-wrap">

    <div class="container-sm">

        <h1><?php  the_title();?></h1>

        <?php get_template_part('includes/section','content');?>
   </div>

   <?php
   $args = array(
       'post_type'=>'post',
       'posts_per_page' => 3
   );
   $_posts = new WP_Query($args);
   ?>
   <?php if($_posts->have_posts()):?>
   <div class="row mt-5">

     <?php while($_posts->have_posts()) : $_posts->the_post();?>

    <?php if(has_post_thumbnail()) {
    $thumbnail_data = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'caursel' );
    $thumbnail_url = $thumbnail_data[0];
}
?>


    <div id="post-<?php the_ID(); ?>"  style="background-image:url('<?php echo $thumbnail_url ?>');width:440px;margin-left:3px;padding:10px; border-radius:10px;display:flex;align:center;" >



        <a href="<?php the_permalink();?>">
        <h3><?php the_title();?></h3>
      </a>
      <h6><?php the_excerpt();?></h6>
    </div>

   <?php endwhile;?>
   </div>
   <?php endif;?>
</section>`


Solution

  • If you have tried ACF and you are accustomed with it, I would go for the 'Relationship' custom field.

    With this field, you can choose what posts can be chosen (I.e by category, tag, etc), as well as the minimum and maximum posts which can be chosen (in your case, maybe one, since it is a featured post).

    Once you have set up this custom field in the back end, you can add a post to the field.

    In your text editor, you can access the ACF like so:

    <?php
      $post_objects = get_field('name_of_acf_relation_field');
      if( $post_objects ) {
         foreach( $post_objects as $single) {
           $ID = $single->ID; ?>
            // write html code here and use your $ID to access the post
            // you can access other custom fields too by using the $ID
            // i.e <?php the_field('field_name', $ID); ?>
          <?php } ?>
      <?php } ?>