简体   繁体   中英

Display related posts based on custom meta field on single WordPress post page?

I'm currently working on a website for a DJ friend of mine who uploads his mixes to Soundcloud to share, he will also be using his website to post his mixes (via Soundcloud) and to post events.

To handle the events side of things, rather than using a custom post type, I simply added my own meta fields to the standard post screen, and set-up the posts to display the event info if it is set, and display the posts normally if not. Full code , relevant part:

global $wp_query;
$postid = $wp_query->post->ID;
$event_venue = get_post_meta($postid, 'event_venue', true);

In addition to this, to handle his mixes, I have set up a custom post type (generally to make it easier for him to distinguish, as he's not terribly techsavvy outside of a mixer and turntables) and custom meta fields to allow him to add where the mix was recorded (venue-wise) and his soundcloud URL to the mix (which is used to automatically embed the mix in the post, rather than using a plugin). I have created a custom loop and single-mixes.php page to handle the display of the data, which is essentially the original loop (renamed to loop-mixes.php so I know what's what) but includes a file mix_data.php . Full code , relevant part:

global $wp_query;
$postid = $wp_query->post->ID;
$mix_venue = get_post_meta($postid, 'mix_venue', true);

Now, my question. I would like, in the single post page, to compare the data held in $mix_venue with every other post that has $event_venue set, and display those posts which are a match (ie, so if a user is viewing a mix, they can then see any upcoming events (and, indeed, any past events) held in the venue in which it was recorded).

But , I'm teaching myself WordPress as I go, and I'm really not entirely sure where to begin with this one.

I see that you solved it, but I'll suggest a re-usable approach.

In your theme's functions.php put this function ( full arguments list for get_posts() ):

function print_event_venues( $mix_venue )
{   
    $args = array(
        'numberposts' => -1,
        'post_type'   => 'post',
        'post_status' => 'publish',
        'meta_key' => 'event_venue', 
        'meta_value' => $mix_venue
        );
    $posts = get_posts( $args );

    // DO NOTHING
    if( !$posts )
        return;

    foreach( $posts as $post )
    {
        // DO YOUR HTML
        echo $post->post_title;
    }
}

Then, in any template, simply call it: print_event_venues( $the_mix_venue ); .

Useful info: When should you use WP_Query vs query_posts() vs get_posts()? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM