Skip Navigation

[Resolved] post previous/next link not ordered by date

This support ticket is created 3 years, 10 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Karachi (GMT+05:00)

This topic contains 8 replies, has 2 voices.

Last updated by dorianS-3 3 years, 9 months ago.

Assisted by: Waqar.

Author
Posts
#1673745

Tell us what you are trying to do?
Use "Post previous link" and "Post next link" inside a Content Template of a custom post type single.
The posts seem to be sorted by date created (or even last edited?).

How can I sort the posts by the custom post type field "mentor-last-name"?

Thanks,
Dorian

#1674397

Waqar
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Hi Dorian,

Thank you for contacting us and I'd be happy to assist.

Your observation is correct and by default, the "wpv-post-previous-link" and the "wpv-post-next-link" shortcodes show the posts with respect to post date.

To show previous and next post links, ordered by a custom field's value, you'll need a custom shortcode:


add_shortcode('show_custom_next_previous_links', 'show_custom_next_previous_links_func');
function show_custom_next_previous_links_func($atts) {

	$a = shortcode_atts( array(
		'field' => '',
	), $atts );

	$current_post_ID = get_the_ID();

	$args = array(
	'posts_per_page' => -1,
	'post_type' => get_post_type( $current_post_ID ),
	'post_status' => 'publish',
	'orderby' => 'meta_value',
	'meta_key' => $a['field'],
	'order' => 'ASC',
	);

	$post_results = get_posts( $args );

	ob_start();

	foreach ( $post_results as $post_result ) {
		$post_results_arr[] = $post_result -> ID;
	}

	if(!empty($post_results_arr)) {
		$found_key = array_search($current_post_ID, $post_results_arr);

		$prev_key = $found_key-1;
		$next_key = $found_key+1;

		if($prev_key >= 0) {
			$prev_link = '" <a href="'.get_the_permalink($post_results_arr[$prev_key]).'" rel="prev">'.get_the_title($post_results_arr[$prev_key]).'</a>';
		}

		if($next_key < count($post_results_arr)) {
			$next_link = '<a href="'.get_the_permalink($post_results_arr[$next_key]).'" rel="next">'.get_the_title($post_results_arr[$next_key]).'</a> "';
		}

		if( ($prev_link) || ($next_link) ) {
			echo '<div class="custom-pagination">';
			echo '<div class="custom-pagination-prev">'.$prev_link.'</div>';
			echo '<div class="custom-pagination-next">'.$next_link.'</div>';
			echo '</div>';
		}
	}
	return ob_get_clean();	
}

The above code snippet can be included through either Toolset's custom code feature ( ref: https://toolset.com/documentation/adding-custom-code/using-toolset-to-add-custom-code/ ) or through active theme's "functions.php" file.

After that, you'll be able to add this shortcode in your content template like this:


[show_custom_next_previous_links field="wpcf-mentor-last-name"]

The last step would be to include some custom CSS code in the content template, to make sure that these links show in a single line, properly aligned:


.custom-pagination {
overflow: hidden;
clear: both;
}

.custom-pagination .custom-pagination-prev {
float: left;
text-align: left;
}

.custom-pagination .custom-pagination-next {
float: right;
text-align: right;
}

I hope this helps and please let me know if you need any further assistance around this.

regards,
Waqar

#1674493

Hi Waqar,

very nice so far, thank you.

A couple of issues I face:

1. this does not seem compatible with WPML? The links are messed up:

1a) the english post .../mentors/dr-marie-theres-thiell/ has a next link to .../mentoren/dr-marie-theres-thiell/
(which is a link to the same post but with the german slug?)
in fact all english posts use german slugs in the links?

1b) .../de/mentoren/dr-marie-theres-thiell/ has a previous link to.../de/mentoren/dr-marie-theres-thiell/ ... the same post?

2. Before the prev and after the next there's a " symbol. Can this be changed to a laquo and raquo?

2a) can laquo/raquo even be part of the link?

2b) could the prev/next links also include a static text string like "previous" and "next"? They would need to be translated.

Thanks,
Dorian

#1674517

3. I just realized the links probably show the post title - could they instead show custom fields
"mentor-first-name" "mentor-last-name"
?

It'd be perfect to have
English:
<< previous - John Doe
Jane Doe - next >>

and German:
<< zurück - John Doe
Jane Doe - vor >>

#1677799

Waqar
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Hi Dorian,

Thanks for the update and I apologize for the delay in getting back on this.

The use of WPML on the website complicates the requirement a bit, so I'll need to perform some tests on my website, to suggest some changes to the custom shortcode.

I'll update you, as soon as this testing completes, and thank you for your patience.

regards,
Waqar

#1683787

Waqar
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Hi Dorian,

Thank you for waiting, while I performed some tests.

To update the custom shortcode so that it works with WPML translated posts, you can replace the old shortcode with this one:


add_shortcode('show_custom_next_previous_links', 'show_custom_next_previous_links_func');
function show_custom_next_previous_links_func($atts) {
 
    $a = shortcode_atts( array(
        'view' => '',
    ), $atts );
 
    $current_post_ID = get_the_ID();
 
    $view_output = do_shortcode('[wpv-view name="'.$a['view'].'"]');

    $view_output_arr = explode(",", $view_output);
 
    ob_start();
 
    if(!empty($view_output_arr)) {
        $found_key = array_search($current_post_ID, $view_output_arr);
 
        $prev_key = $found_key-1;
        $next_key = $found_key+1;
 
        if($prev_key >= 0) {

            $prev_name = do_shortcode('[types field="mentor-first-name" item="'.$view_output_arr[$prev_key].'"][/types] [types field="mentor-last-name" item="'.$view_output_arr[$prev_key].'"][/types]');

            $prev_link = '<a href="'.get_the_permalink($view_output_arr[$prev_key]).'" rel="prev">'.do_shortcode('[wpml-string context="wpv-views"]&laquo; previous[/wpml-string]').' - '.$prev_name.'</a>';
        }
 
        if($next_key < count($view_output_arr)) {

            $next_name = do_shortcode('[types field="mentor-first-name" item="'.$view_output_arr[$next_key].'"][/types] [types field="mentor-last-name" item="'.$view_output_arr[$next_key].'"][/types]');

            $next_link = '<a href="'.get_the_permalink($view_output_arr[$next_key]).'" rel="next">'.$next_name.' - '.do_shortcode('[wpml-string context="wpv-views"]next &raquo;[/wpml-string]').'</a>';
        }
 
        if( ($prev_link) || ($next_link) ) {
            echo '<div class="custom-pagination">';
            echo '<div class="custom-pagination-prev">'.$prev_link.'</div>';
            echo '<div class="custom-pagination-next">'.$next_link.'</div>';
            echo '</div>';
        }
    }
    return ob_get_clean();  
}

This shortcode will need a post view to get the IDs of the posts, instead of the "get_posts" function, because a post view will automatically update the results, based on the current language.

You'll create a new post view for your post type for which you'd like to use these next and previous links and set it to be ordered by the "mentor-last-name" field.

In the view's "Loop Editor" wizard, you'll select "List with separators" format for the output and only include the post ID shortcode so that this view's output only consists of the comma-separated list of post IDs:


[wpv-layout-start]
	[wpv-items-found]
	<!-- wpv-loop-start -->
		<wpv-loop>
			[wpv-item index=other]
				[wpv-post-id],
			[wpv-item index=last]
				[wpv-post-id]
		</wpv-loop>
	<!-- wpv-loop-end -->
	[/wpv-items-found]
	[wpv-no-items-found]
		<strong>[wpml-string context="wpv-views"]No items found[/wpml-string]</strong>
	[/wpv-no-items-found]
[wpv-layout-end]

The last step would be to include the custom shortcode in the content template where you'd like to show the next and previous links:
( the custom CSS code will remain the same as shared in the last message )


[show_custom_next_previous_links view="new-view-slug"]

Note: You'll replace "new-view-slug" with the actual name or slug of the newly created post view.

Important note: The custom code snippets that we provide are just to share some ideas that can help in getting started in the right direction. But it won't be possible for us to continue providing 1-1 customization assistance, over the forum.
( ref: https://toolset.com/toolset-support-policy/ )

For more personalized assistance around custom code, you can consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/

regards,
Waqar

#1683881

Thanks, Waqar.
Befre I try to set up the new post view - would that mean that the post IDs would need to be entered manually instead of simply using all published posts from that custom post type? That would be a bit of a pain.

#1683889

Waqar
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Hi Dorian,

The post view that you'll create should fetch the post IDs of the published posts in the correct order, automatically.

You won't have to provide the IDs manually.

regards,
Waqar

#1686739

My issue is resolved now. Thank you!

This ticket is now closed. If you're a WPML client and need related help, please open a new support ticket.