[Resolved] The most recent post on hero page of specific category

Home Forums Support The most recent post on hero page of specific category

  • This topic has 3 replies, 2 voices, and was last updated 12 months ago by Tom.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #1014410
    An Nguyen

    Hi All,

    I used the below code for displaying the most recent post of specific category (96) on my archive page (3486), but I got an issue that the feature-image display incorrectly. Its real image is different from this. (You can view link update and move to blog to see the real image.)

    I need you help on this code.

    add_shortcode( 'most_recent_hero_post_archives', function() {
        $latest_posts = get_posts( 'numberposts=1&category=96' );
        $latest_id = $latest_posts[0]->ID;
        $date_format = get_option( 'date_format' );
        setup_postdata( $latest_posts[0] );
        add_filter( 'excerpt_more', 'tu_no_read_more', 1000 );
        add_filter( 'excerpt_length', 'tu_change_excerpt_length', 1000 );
    
        $return = '<h2>' . get_the_title( $latest_id ) . '</h2>';
        $return .= '<div class="hero-date">' . get_the_date( $date_format, $latest_id ) . '</div>';
        $return .= '<div class="hero-excerpt">' . get_the_excerpt( $latest_id ) . ' ...</div>';
        $return .= '<a class="button hero-button" href="' . get_permalink( $latest_id ) . '">Read more</a>';
    
        remove_filter( 'excerpt_more', 'tu_no_read_more', 1000 );
        remove_filter( 'excerpt_length', 'tu_change_excerpt_length', 1000 );
    
        wp_reset_postdata();
    
        return $return;
    } );
    
    function tu_no_read_more() {
        return '';
    }
    
    function tu_change_excerpt_length() {
        return 35;
    }
    
    add_filter( 'pre_get_posts', function( $query ) {
        if ( $query->is_category( 96 ) && $query->is_main_query() ) {
            $query->set( 'offset', '1' );
        }
    } );
    
    add_filter( 'generate_page_hero_background_image_url', function( $image_url, $options ) {
        if ( 3486 === $options['element_id'] ) {
            $latest_posts = get_posts( 'numberposts=1' );
            $latest_id = $latest_posts[0]->ID;
    
            $image_url = get_the_post_thumbnail_url( $latest_id );
        }
    
        return $image_url;
    }, 3486, 2 );
    #1014935
    Tom
    Lead Developer
    Lead Developer

    Hi there,

    In your background image url filter, you have this:

    $latest_posts = get_posts( 'numberposts=1' );

    Try this:

    $latest_posts = get_posts( 'numberposts=1&category=96' );

    #1014942
    An Nguyen

    Hi Tom,

    The issue is solved.

    Thanks Tom.

    #1015331
    Tom
    Lead Developer
    Lead Developer
Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.