Archived topic
What is selector for the last post in kategory?
4 replies · Started by Olga on December 1, 2016
Hello!
I have the sidebar widget which always links to last post from the certain category: http://joxi.ru/RmzYEdetxO74rO
To do this I use the code:
<a href="/*There is the url of last post from category*/"><img src="" /></a>
I change the post's url in widget link manually, when new post is published in this category.
Can I automatize this process? Is there any selector which means the last post from certain category?
Hi Olga,
Thank you for reaching out to us.
I personally have never used a workable way of automating a link URL to a latest post within a certain category within the sidebar widget wrapping an image! :-)
Tom works miracles and may well know how to do this, but I think it will involve some PHP magic...
WordPress.org gives you some examples of how to do this in PHP so please read this guide:
https://codex.wordpress.org/Function_Reference/wp_get_recent_posts
Let's give it a go though...
I think it will require some PHP coding and possibly even this plugin for a PHP Text Widget where we cna then put our own PHP code in place, so go and install this plugin:
https://en-gb.wordpress.org/plugins/php-text-widget/
Then using this new widget in your sidebar, try inserting this code into that PHP Text Widget, and make sure you insert your image URL in place, and you replace the CAT_ID with the ID number of the category itself:
<?php
$args = array( 'numberposts' => '1', 'category' => CAT_ID );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<a href="' . get_permalink($recent["ID"]) . '"><img src="YOUR IMAGE URL" alt="YOUR IMAGE ALT TEXT" /></a>';
}
?>
I would very much like to know if this actually works or not.
That could definitely work, Richard - nice find! Although I'm not sure how much I trust that plugin.
After a quick Google I found this which is interesting: http://wordpress.stackexchange.com/a/129059/90661
Looks like you could just put that function into your functions.php file/custom plugin/Code Snippets plugin and then link to the latest post using ?latest after the category name.
Might be another method to try :)
Thank you very much, guys! Richard, your code really helped!
And there is no need for any plugin to add this code, I just added it to GP Hooks -> Before Right Sidebar and everything is work.
http://joxi.ru/a2XWz5xhjLXDmg.png
Awesome! :)