jesperfrimann
Member
Posted 4 months ago #
Hi
I am listing all my custum posttype categories as links, but i don't want them to link to the category archive. Instead I want them to link to the first post of that particular category.
Somehow I need to get the permalink of the first post of each category.
Can anyone tell me how to do that?
Tanks.
What function do you use to list the categories?
jesperfrimann
Member
Posted 4 months ago #
Thanks for You reply keeslemeijer.
Here is the code I'm using to list my categories.
You should know, that I'm using custom taxonomies "pattern-categories" and I have included all the markup, which result in a linkable imagerepresentation of each category.
What I would like to change is the link destination so it links to the first post in the given category.
I hope You can help me.
[Code moderated as per the Forum Rules. Please use the pastebin]
Try it with by using get_posts() in your foreach($categories as $category) {
This will fetch the first post in the category and uses get_permalink() to get the url of the first post.
foreach($categories as $category) {
$first_cat_post = get_posts('posts_per_page=1&cat='.$category->term_id);
echo '<a href="'.get_permalink( $first_cat_post[0]->ID ) .'" title="View first post from category: '.esc_attr( $category->name ).'" style="text-decoration:none;">
<li class="left-side">
<!-- rest of your code -->
';
jesperfrimann
Member
Posted 4 months ago #
Thanks
Almost the way I want it. However, all links are identical and leads to the same post.
Does that post have all those categories assigned to it?
jesperfrimann
Member
Posted 4 months ago #
No. Only one category is assigned to that post...
try changing this:
$first_cat_post = get_posts('posts_per_page=1&cat='.$category->term_id);
to this:
$args = array(
'category__in' => array($category->term_id),
'posts_per_page' => 1
);
$first_cat_post = get_posts($args);
jesperfrimann
Member
Posted 4 months ago #
Thats's strange this works on my testsite. Can you paste and submit the full code of the template file this is in into a pastebin.com and post the link to it here? see the Forum Rules for posting code and using the pastebin.
Maybe clear your browsers cache?
jesperfrimann
Member
Posted 4 months ago #
jesperfrimann
Member
Posted 4 months ago #
Maybe put the custom post type in the $args array:
$args = array(
'post_type' => 'mycustomposttype', // change this to the post type you registered
'posts_per_page' => 1,
'tax_query' => array(
array(
'taxonomy' => 'pattern-categories',
'field' => 'id',
'terms' => array($category->term_id)
)
)
);
$first_cat_post = get_posts($args);
Change "mycustomposttype" to the custom post type you registered.
And remove one of the
$first_cat_post = get_posts($args);
jesperfrimann
Member
Posted 4 months ago #
keesiemeijer, You are a genius. It works just the way it is supposed to.
Thank You very much for You efforts. I really appreciate it.
//Jesper
No problem. Glad you got it resolved.