Search code examples
wordpressadvanced-custom-fieldscustom-post-type

Sorting custom post types depends on ACF Date Field


My task is to sort all the custom post types ('audio', 'video', 'webdev' etc.) gathered by taxonomy 'portfolio' or by any tag. And I do it with following code.


    add_filter( 'pre_get_posts', 'custom_post_types_sort' );

    function custom_post_types_sort( $query ) {

        if ( is_tax('portfolio') || is_tag() ) {

            $cptui_post_types = cptui_get_post_type_slugs();

            // Sort portfolio taxonomy posts by project start date.
            $query->set( 'post_type', $cptui_post_types );
            $query->set( 'order', 'DESC' );
            $query->set( 'orderby', 'meta_value_num' );
            $query->set( 'meta_key', 'date' );
        }
    }

?>

Everything works fine except one thing. My menu not showing on the taxonomy template. I'm using taxonomy-portfolio.php template to display pages.

I assume this is happening because of query modification.

<?php 
    /**
    *    Portfolio Taxonomy Template
    */
    get_header();
?>

<section class="portfolio-template swiper">
    <div class="swiper-wrapper postfolio-list">
        <div class="swiper-slide">
            <?php get_template_part( 'template-parts/breadcrumbs' ); ?>
            <div class="portfolio-project-items">
                <?php if ( have_posts() ) : ?>
                    <?php while ( have_posts() ) : the_post(); ?>
                        <?php get_template_part( 'template-parts/content', 'portfolio-item' ); ?>
                    <?php endwhile; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<?php get_footer(); ?>

Solution

  • Replace this

    if ( is_tax('portfolio') || is_tag() ) {
    

    by this

    if ( ( is_tax('portfolio') || is_tag() ) && $query->is_main_query() ) {
    

    Check the docs: https://developer.wordpress.org/reference/functions/is_main_query/

    This function is most commonly used within hooks to distinguish WordPress’ main query (for a page, post, or archive) from a custom/secondary query.

    Does this fix your problem?