I am buidling a wordpress blog. I have a post category ‘wmp’, which includes an ACF called ‘mvs’. Every time I post a new ‘wmp’ I would like to display the ‘mvs’ of that most recent ‘wmp’ post on a page.
I’m a complete non-code rookie relying on shortcodes largely, and I’m trying to read out that last ‘mvs’ value. I have gotten so far to use the shortcode to call the ACF field for a specific post ID.
[acf field="mvs" post_id=9871]
It works but I have to put in a specific post which is not what I want – I need this to be the ID of the last post of the category.
I have been searching for hours and I just cannot find a solution – there are some threads on similar topics (e.g. Get the second last post in a category) but I have not enough coding experience to adapt any of those php codes to my problem, nor do I know where to insert this code at all and how to use it in my frontend with a shortcode.
Ideally I need some basic code snippet that I can load into the functions.php with the "Code Snippets" wordpress plugin, and then access that with a shortcode. Does anybody have a recommendation?
EDIT:
Thanks for the answer … I’ve exchanged $category_id with my category ID (’14’), and put the code in a snippet for functions.php. How do I call this with a short code? I’ve tried [acf field="mvs" post_id=$post_id] but that doesn’t work ….
2
Answers
Thanks Im-Shaoib, that was a great help.
I fumbled around a bit and added in some other code I found on the web and got it to work in the end. For any other noob like me that is suffering with the same problem, put the following code into the snippet that will be added to functions.php:
where 'category' is the ID of your post type (you can find this in wordpress under post categories and then hover over the post type entry, the appearing permalink will contain the ID number) and then call the ACF value from the last post in a short-code on the front end with:
To get the post ID of the last post in a specific category in WordPress, you can use the WP_Query class to create a new query that retrieves the latest post in that category.
Here is the example code.
you can change the $category_id with your category id.
order by date gets the last add post with the DESC order of that category.