• Hi, I would like to create next post adjacent post and it works as expected, but if there is no next post I got this warning:
    Attempt to read property “ID” on string
    the same warning for the previous post if there is no previous post, what should I do?
    here is my code:

    <?php
    $next_post = get_adjacent_post(0, '', 0);
    $link_address =get_permalink($next_post->ID);
    $title=get_the_title();
    if( $next_post )
    echo "<a href='".$link_address."'>
    <div class='izdan-adjacent'>
    <div>
    <div class='izdan-adjacent-title'> Berikutnya </div> <div>$next_post->post_title </div>
    </div>
    <div class='izdan-adjacent-icon'>
    <svg xmlns='https://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' class='bi bi-chevron-right' viewBox='0 0 16 16'>
      <path fill-rule='evenodd' d='M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z'/>
    </svg>
    </div>
    </div>
    </a>";
    ?>
    
    

    Note: the waring is on PHP 8 and there is no warning on PHP 7.4

    thank you.

    • This topic was modified 2 years, 6 months ago by Jan Dembowski.
Viewing 2 replies - 1 through 2 (of 2 total)
  • That would be coming from this line:

    $link_address =get_permalink($next_post->ID);

    Youv’e got that too early in your code. You do the check for $next_post two lines down – after you’ve attempted to get a value from an object that doesn’t exist (in the case of no adjacent post being available).

    Just move that ine into the check branch with the rest and it should be all fine.

    $next_post = get_adjacent_post(0, '', 0);
    $title=get_the_title ();
    
    if( $next_post ) {
    	$link_address = get_permalink($next_post->ID);
    	echo "<a href='".$link_address."'>
    	<div class='izdan-adjacent'>
    	<div>
    	<div class='izdan-adjacent-title'> Berikutnya </div> <div>$next_post->post_title </div>
    	</div>
    	<div class='izdan-adjacent-icon'>
    	<svg xmlns='https://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' class='bi bi-chevron-right' viewBox='0 0 16 16'>
    	  <path fill-rule='evenodd' d='M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z'/>
    	</svg>
    	</div>
    	</div>
    	</a>";
    }
    Thread Starter Mohammad Ridwanullah

    (@readonecc)

    Thank you very much! You saved my life.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Attempt to read property “ID” on string’ is closed to new replies.