Support

Account

Home Forums General Issues get previous and next post link in post objects Reply To: get previous and next post link in post objects

  • Yes, i already revised the code and this works:

    function post_object_navigation_shortcode() {
    	global $post;
    
    	// get the post/page id where post object field is added.
    	$course_id = get_field( 'lesson_of_course' );
    
    	// get current post id, this can be also a post object.
    	$current_post_link_id = get_the_ID();
    
    	// get all the post_link sub field values.
    	$post_objects = array();
    
    	if ( have_rows( 'lesson_listing', $course_id ) ) :
    		while ( have_rows( 'lesson_listing', $course_id ) ) :
    			the_row();
    
    			// check for rows (sub repeater)
    			if ( have_rows( 'section_repeater', $course_id ) ) :
    
    				while ( have_rows( 'section_repeater', $course_id ) ) :
    					the_row();
    
    					$my_field = get_sub_field( 'post_link' );
    					if ( ! empty( $my_field ) ) {
    						$post_objects[] = $my_field;
    					}
    
    				endwhile;
    			endif;
    		endwhile;
    	endif;
    
    	// get the current index of the current post object
    	$current_index = array_search( $current_post_link_id, array_column( $post_objects, 'ID' ) );
    
    	// output the previous post object title and link
    	if ( $current_index > 0 ) {
    		$previous_post = $post_objects[ $current_index - 1 ];
    		$post = get_post( $previous_post );
    		setup_postdata( $post );
    		$title = get_the_title();
    		$link = get_the_permalink();
    		echo '<a href="' . esc_url( $link ) . '">' . esc_html( $title ) . '</a>';
    	}
    
    	// output the next post object title and link
    	if ( $current_index < count( $post_objects ) - 1 ) {
    		$next_post = $post_objects[ $current_index + 1 ];
    		$post = get_post( $next_post );
    		setup_postdata( $post );
    		$title = get_the_title();
    		$link = get_the_permalink();
    		echo '<a href="' . esc_url( $link ) . '">' . esc_html( $title ) . '</a>';
    	}
    
    	wp_reset_postdata();
    }
    add_shortcode( 'lesson_navigation', 'post_object_navigation_shortcode' );