简体   繁体   中英

Wordpress PHP: Combining posts with custom post types on category archive

I have a site with Wordpress posts and a custom post type (molinks). I have a post loop (plugin driven) that displays both posts and molinks in the same way. The problem I am trying to fix is that when the user clicks on the category tags, to see the category archive page, only the posts with that category show up (not the molinks).

To fix this I have used the following code, however it only works if there is a post with the category. ie if a post and a molink have category A then both will show on the category A archive page. But if only the molink has category A (and not a post) then the molink with the category does not show. In this case the template 'none' is called (line 2nd from bottom).

Any ideas? Thanks

    <?php
    /* Start the Loop */
    while ( have_posts() ) : the_post();
    $args = array(
        'post_type' => array('molink', 'post'),
    'category__in' => get_queried_object_id(),
        'showposts' => 100
            );
    $custom_posts = new WP_Query( $args );
    if ( $custom_posts->have_posts() ):
        while ( $custom_posts->have_posts() ) : $custom_posts->the_post();?><br />
    <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>"><br />
    <?php the_title(); ?></a>, <br />
    <?php the_time('d M Y'); ?><br />   
    <?php endwhile; else: ?><br />
        <p><?php _e('No posts.'); ?></p><br />
    <br />
        <?php endif; ?> <br />
    <?php
    endwhile;
?>

    <?php else : ?>
    <?php get_template_part( 'content', 'none' ); ?>
    <?php endif; ?>

The main problem you are having is that you are executing the second $customer_posts query only if the original WordPress query (that only checks the regular post_type) has results.

So what happens is it will be never called when you are only having molink in your category A.

The best way around it, in my opinion, is to use the pre_get_posts WordPress hook, which you can find more details about Here .

Fires after the query variable object is created, but before the actual query is run.

You should create a code that would look something like the following example:

// Somewhere around functions.php
function add_molinks_to_post_archives ( $query ) {

    // Only apply when is main category, inside inside a category page
    if ( is_category() && $query->is_main_query() ) {
        $query->set( 'post_type', array( 'post', 'molink' ) );
    }
}

add_action ( 'pre_get_posts', 'add_molinks_to_post_archives' );

And then, you can just skip the custom code inside the loop itself.

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