I've done considerable research, and tried multiple solutions to my task, and currently have found a way but i know it is not the best, so hoping for input to do this better.
The task
I am using Shortcode in Menus plugin combined with custom shortcodes to display between one and three of the latest blog posts in my site's main menu.
For each menu link, it's a menu item added using that plugin, with the title and link each set via a different shortcode:
The way it will work, is I have three menu items added in WordPress menu editor, each using a shortcode to pull one post - one pulls the most recent, one pulls the next most recent, and so on. I currently have 2 shortcodes - one pulling title, one pulling permalink. (This question is not technically about it, but I think i could do it with one shortcode, and $atts
to grab title or link, so feel free to chime on that too).
The issue with my code
This pulls the latestlink ok, but to pull the second most recent, i tried using offest
- which is commented out below, as it was pulling the most recent - but setting offset
to 2
, or 3
, does not do anything. What does work, is setting 'posts_per_page' => 3, 'offest' => 3,
.
add_shortcode('latest_blog_post_link', 'get_latest_blog_post_link');
function get_latest_blog_post_link($atts, $content = null) {
$args = array(
'posts_per_page' => 1,
// 'offest' => 1,
'cat' => '38, 21, 30, 39, 10, 8, 26, 20, 22, 18, 9, 24, 11' // replace this number with your category's ID
);
$posts = get_posts($args);
foreach($posts as $post) {
$latest_post = get_permalink($post);
}
return $latest_post;
}
So my question is, is there a better way to do this? Do I have to set posts_per_page
to a value higher than 1
for offset to work?
offset
- you used offest.. So try with'offset' => 1
?offset
typo