I'm trying to generate a hyperlink on my homepage for the most recent post using wp_get_recent_posts()
and in_category()
. The site is not setup like a blog—post excerpts and custom fields are being loaded into custom page templates using categories with dynamic #id based on slug, and all that works fine. So, I'm trying to get the category of the most recent post and then generate the link for it with the proper URL based on category since that's how I can differentiate what page they're on.
I tested the structure of the link generation outside of the if else and it works fine. But it's not working inside the if else statements: echo $before . $homeURL . "audio/" . "#" . $slug . $after;
I'm not a programmer so it may be a stupid mistake. One thing I did notice is that if I print the array $recent
, there seems to be no category name or category number in it, even if I specify the categories in the $args
array using 'category' => '2,3,4,5'
.
I managed to work this out thanks to the help of someone on WordPress.org, so the below code is now functioning properly using the has_category()
function.
<?php
$args = array( 'numberposts' => '1', 'offset' => '0', 'orderby' => 'post_date', 'order' => 'DESC', 'post_status' => 'publish' );
$recent_posts = wp_get_recent_posts( $args );
$home = home_url( '/' );
$homeURL = esc_url( $home );
$before = '<a href="';
$after = '">dive in</a>';
foreach( $recent_posts as $recent ){
$slug = basename( get_permalink($recent["ID"]) );
// if post is audio
if ( has_category('audioz', $recent["ID"]) ) {
echo $before . $homeURL . "audio/" . "#" . $slug . $after;
}
// else if post is video
else if ( has_category('videoz', $recent["ID"]) ) {
echo $before . $homeURL . "videos/" . "#" . $slug . $after;
}
// else if post is article
else if ( has_category('articlez', $recent["ID"]) ) {
echo $before . $homeURL . "article/" . "#" . $slug . $after;
}
// else if post is zazzle link
else if ( has_category('zazzle', $recent["ID"]) ) {
echo $before . $homeURL . "store/" . "#" . $slug . $after;
}
}
?>
is_category() checks if the page you're currently on is a category archive page, and more specifically if it is the specified category's archive page. In all of your cases, this would return false
.
I believe the function you're actually looking for is in_category() and the if statement would look something like this:
/* Needs to have post object ($recent) so it knows what to check */
if ( in_category('audioz', $recent) ) {
echo $before . $homeURL . "audio/" . "#" . $slug . $after;
}