mercredi 8 juin 2016

WordPress: using if else with wp_get_recent_posts

I'm trying to generate a hyperlink on my homepage for the most recent post using wp_get_recent_posts() and is_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' .

The homepage template is hard-coded as it's not loading any posts into it, so maybe I need to use this stuff in a loop to make it work right??

<?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 ( is_category('audioz') ) {
            echo $before . $homeURL . "audio/" . "#" . $slug . $after;
        }
        // else if post is video
        else if ( is_category('videoz') ) {
            echo $before . $homeURL . "videos/" . "#" . $slug . $after;
        }
        // else if post is article
        else if ( is_category('articlez') ) {
            echo $before . $homeURL . "article/" . "#" . $slug . $after;
        }
        // else if post is zazzle link
        else if ( is_category('zazzle') ) {
            echo $before . $homeURL . "store/" . "#" . $slug . $after;
        } 
    }
?>

I also tried using the category number in is_category() but that didn't work, and I also tried using in_category().

Advice welcome. I've been at this for hours and can't find anything about this on here, the wordpress.org forums, or through web searches. I can't link to the page as I only have the ability to work locally at the moment in MAMP.

thanks

Aucun commentaire:

Enregistrer un commentaire