• Resolved Paul Taylor

    (@pftaylor61)


    I would like to add some code to my header.php which will get the link-address and the heading for a single post – my post recent post in one particular category. This should not affect the remainder of the page, which may well include a call to the_loop().

    I need something like this:

    <p>Latest News: <a href=”
    <?php echo {url here}; ?>
    “>
    <?php echo {post heading here}; ?>
    </p>

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter Paul Taylor

    (@pftaylor61)

    Let’s try doing the code properly this time!

    <p><strong>Latest News: </strong><a href="
    <?php echo {url here}; ?>
    ">
    <?php echo {post heading here}; ?>
    </a>
    </p>

    Something like this should work:

    <?php
    $args = array(
      'cat'            => 21,
      'posts_per_page' => 1
    );
    
    $new_query = new WP_Query( $args );
    
    if ( $new_query->have_posts() ) :
      while ( $new_query->have_posts() ) : $new_query->the_post(); ?>
        <p><strong>Latest News:</strong>
          <a href="<?php echo esc_url( the_permalink() ); ?>"><?php the_title(); ?></a>
        </p>
      <?php endwhile;
    endif;
    
    wp_reset_postdata();
    ?>

    Substitute the numeric ID of the desired category for ’21’. Calling wp_reset_postdata() prevents this code from affecting the rest of the page.

    Thread Starter Paul Taylor

    (@pftaylor61)

    This is perfect.

    I wrapped this all up in a function, and put it in the functions.php of my child theme, and then put a call to the function in the header.php.

    Thank you very much for your time – I appreciate it.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Most Recent Post’ is closed to new replies.