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' );
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
Are you building WordPress sites with ACF and @BeaverBuilder, and wanted to use your ACF Blocks in both the block editor and Beaver Builder?
— Advanced Custom Fields (@wp_acf) May 10, 2023
The BB team recently added support for using ACF Blocks in Beaver Builder. Check it out 👇https://t.co/UalEIa5aQi
© 2023 Advanced Custom Fields.
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.