Несколько циклов на странице показывают только название таксономии первого цикла


У меня есть страница с пользовательским типом записи "книги" с таксономией "типы книг". Книги упорядочены/разделены в цикле по элементам таксономии и добавлены с помощью шорткода в редактор страниц следующим образом:

[books booktypes="cityguides"]
[books booktypes="travelguides"]
[books booktypes="languageguides"]

Итак, у меня есть, например:

(цикл 1)

ПУТЕВОДИТЕЛИ ПО ГОРОДУ

Путеводитель по городу 1
Путеводитель по городу 2
Путеводитель по городу 3
и т.д.

(цикл 2)

ПУТЕВОДИТЕЛИ

Путеводитель 1
Путеводитель 2
Путеводитель 3
и т.д.

(цикл 3)

ЯЗЫКОВЫЕ РУКОВОДСТВА

Языковой справочник 1
Языковой справочник 2
Языковой справочник 3
и т.д.

Теперь я хочу, чтобы имя таксономии отображалось в верхней части каждого цикла типа книги.

У меня есть следующий код, но он показывает только название таксономии первого типа книг (Cityguides) в каждом цикле. Должно быть, я делаю что-то не так в этом порядке, но я просто не могу понять, что именно.

<?php
// create shortcode with parameters so that the user can define what's queried - default is to list all blog posts
add_shortcode('books','books_shortcode');

function books_shortcode( $atts ) {
    ob_start();
    extract( shortcode_atts( array (
        'type'      => 'books',
        'order'     => 'name',
        'order'     => 'ASC',
        'orderby'   => 'title',
        'posts'     => -1,
        'booktypes' => '',
        'category'  => ''
    ), $atts ) );

    $options = array(
        'post_type'         => $type,
        'order'             => $order,
        'orderby'           => $orderby,
        'posts_per_page'    => $posts,
        'booktypes'         => $booktypes,
        'category_name'     => $category
    );
    $query = new WP_Query( $options );

    $taxonomy = 'booktypes';
    $queried_term = get_query_var($taxonomy);
    $terms = get_terms($taxonomy, 'slug='.$queried_term);

    if ($terms) {
        foreach($terms as $term) {

            if ( $query->have_posts() ) {

                 ?>

                    <h2 id="<?php echo $booktypes ?>" style="margin:0px 0px 20px 0px; ">
                        <?php
                            echo $term->name;
                        ?>
                    </h2>

                    <div class="books-container <?php echo $booktypes ?>">

                        <?php while ( $query->have_posts() ) : $query->the_post(); ?>

                            <?php if( $query->current_post%3 == 0 ) echo "\n".'<div class=" section_inner clearfix"><div class="section_inner_margin clearfix">'."\n"; ?>

                                <div <?php post_class('vc_span4 wpb_column column_container'); ?> style="padding-bottom: 60px;">
                                    <div class="wpb_wrapper">

                                        <?php // Get the post thumbnail ?>
                                        <div class="wpb_single_image wpb_content_element element_from_fade element_from_fade_on">
                                            <div class="wpb_wrapper">
                                                <?php 
                                                    if ( has_post_thumbnail() ) {
                                                        //$large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'Book-thumbnail' );
                                                        echo '<a href="' . get_permalink( $thumbnail->ID ) . '" title="' . the_title_attribute( 'echo=0' ) . '" class="book-holder" ><span class="book-thumb">';
                                                        echo get_the_post_thumbnail( $post->ID, 'book-thumbnail' ); 
                                                        echo '</span></a>';
                                                    }
                                                ?>
                                            </div> 
                                        </div>

                                    </div>

                                    <div class="wpb_text_column wpb_content_element text-align-center" style="margin: 20px 0px 0px 0px; ">

                                        <div class="wpb_wrapper">
                                            <h5><?php the_title(); ?></h5>
                                        </div>
                                        <a href="<?php the_permalink(); ?>" target="_blank" class="qbutton  small" style="margin: 20px 0px 0px 0px; "><?php _e('More Info', 'qode'); ?></a>

                                    </div>

                                </div>

                            <?php if( $query->current_post%3 == 2 || $query->current_post == $query->post_count-1 ) echo '</div></div> <!--/.wrap-->'."\n"; ?>

                        <?php endwhile;
                        wp_reset_postdata(); ?>
                    </div>

            <?php 
                $myvariable = ob_get_clean();
                return $myvariable;
            }
        }
    }
}
?>
Author: Pieter Goosen, 2015-06-23

1 answers

Как я уже говорил, вы можете сделать все вышеперечисленное в своем вопросе только с одним шорткодом. Идея здесь состояла бы в том, чтобы

  • Используйте usort() для сортировки сообщений по названию термина

  • Передайте строку названий терминов в том порядке, в котором они должны отображаться, в шорткод

НЕСКОЛЬКО ВАЖНЫХ ЗАМЕЧАНИЙ

  • Никогда не используйте extract(). Он ненадежен и чрезвычайно сложен в отладке, когда он выходит из строя. Из-за этого использование extract() было удален из ядра и кодекса. Вы можете прочитать больше об этом в следующем билете trac: билет trac #22400

  • В вашем коде довольно много ошибок, большинство из них теперь исправлены. Однако в следующей строке кода осталось два

    echo '<a href="' . get_permalink( $thumbnail->ID ) . '" title="' . the_title_attribute( 'echo=0' ) . '" class="book-holder" ><span class="book-thumb">';
    

    $thumbnail не определено, я не уверен, как на самом деле должна выглядеть эта строка, поэтому вам нужно будет разобраться в этом самостоятельно. Для целей отладки я лично использую плагин под названием Объекты отладки (, к которому я не имею никакого отношения ) в моей локальной тестовой установке для целей отладки. Этот плагин улавливает все ошибки и выводит их на экран.

  • Я прокомментировал код, чтобы было легко понять, что я сделал. В нескольких местах я оставил заметки, в которых я не очень уверен в том, какими должны быть фактические значения. обязательно проверьте их

  • Я добавил атрибут под названием term_order. Если этот атрибут оставить пустым, все термины отображаются в алфавитном порядке. Вы также можете указать конкретный порядок по имени термина ( Я использую здесь имена терминов, так как кажется, что ваш клиент будет передавать имена терминов, а не пули или идентификаторы. Если вы собираетесь передавать идентификаторы или пули, просто измените код соответствующим образом). Этот атрибут принимает строку имен терминов, разделенных запятыми, в том порядке, в котором вы хотите их отобразить. Например:

    term_order="cityguides, travelguides, languageguides"
    

    , в котором будут отображаться сообщения только из этих трех терминов, в порядке cityguides, travelguides, languageguides. Названия терминов будут отображаться только перед первым сообщением в этом конкретном термине

  • В usort() уже много-много лет существует ошибка, и до сих пор она не исправлена. Это ошибка

    Usort(): Массив был изменен функцией сравнения пользователей

    До сих пор, как я уже сказал, эта ошибка все еще не исправлена. Лучшее решение - отключить отчеты об ошибках для этой проблемы, используя знак @ перед usort(). Пожалуйста, обратите внимание, вы должны никогда не использовать этот метод для подавления ошибок и ошибок, все ошибки и ошибки должны быть исправлены. Поскольку это ошибка ядра php, которая, похоже, никогда не будет исправлена, рекомендуется использовать этот метод до тех пор, пока ошибка не будет исправлена. Смотрите подробную информацию об ошибке здесь

  • Этот шорткод надежен только в том случае, если сообщение относится к одному термину. Если к сообщению прикреплено более одного термина, название термина, отображаемое поверх сообщений, может иметь неожиданные эффекты. Для сообщений с несколькими сроками, возможно, было бы лучше использовать отдельные короткие коды или расширить мой код, чтобы справиться с этим

  • У меня есть встроенная система для удаления пробелов до и после запятой при передаче имен терминов в атрибут term_order. Таким образом, вам не нужно беспокоиться о пробелах и сбое шорткода из-за этого

  • Важное примечание: к сообщению должен быть прикреплен хотя бы один термин. Сообщения без условий приведут к ошибкам и шорткоду неудача. Я не принял никаких мер предосторожности для этого из-за ограничений по времени из-за личных проблем, возникших на этой неделе. Вы можете расширить шорткод, чтобы приспособиться к таким ситуациям, когда в публикации нет никаких условий

  • Измените и используйте код по мере необходимости

  • Этот код нуждается в PHP 5.4+ из-за использования синтаксиса короткого массива ([]) в пользу старого синтаксиса (array()). Я также использовал разыменование массива (get_the_terms( $post->ID, $taxonomy )[0]->name) который также доступен только в PHP 5.4+

ВОТ КОД

// create shortcode with parameters so that the user can define what's queried - default is to list all blog posts
add_shortcode( 'books', 'books_shortcode' );

function books_shortcode( $atts ) {
    ob_start();
    // Do not use extract(), use this syntax for your attributes
    $attributes = shortcode_atts( 
        [
            'term_order' => '', // New attribute to sort your terms in a custom order, pass a comma deliminated spaced string here. Default is term name
            'taxonomy'   => 'booktypes',
            'type'       => 'books',
            'order'      => 'ASC',
            'orderby'    => 'post_title',
            'posts'      => -1,
        ], 
        $atts 
    );

    $taxonomy = filter_var( $attributes['taxonomy'], FILTER_SANITIZE_STRING );
    // Check if our taxonomy is valid to avoid errors and bugs. If invalid, return false
    if ( !taxonomy_exists( $taxonomy ) )
        return false;

    //Set the variables for sorting purposes    
    $orderby = filter_var( $attributes['orderby'], FILTER_SANITIZE_STRING );
    $order   = filter_var( $attributes['order'], FILTER_SANITIZE_STRING );

    // Convert the string of term names to an array
    $tax_query = [];
    if ( $attributes['term_order'] ) {
        // First we need to remove the whitespaces before and after the commas
        $no_whitespaces = preg_replace( '/\s*,\s*/', ',', filter_var( $attributes['term_order'], FILTER_SANITIZE_STRING ) );
        $terms_array = explode( ',', $no_whitespaces );

        /*
         * As we are using term names, and due to a bug in tax_query, we cannot pass term names to a tax_query
         * We are going to use get_term_by to get the term ids
         */
        foreach ( $terms_array as $term ) {
            $term_ids_array[] = get_term_by( 'name', $term, $taxonomy )->term_id;
        }

        // Build a tax_query to get posts from the passed term names in $attributes['term_order']
        $tax_query = [
            [
                'taxonomy'         => $taxonomy,
                'terms'            => $term_ids_array,
                'include_children' => false
            ],
        ];

    }

    // Pass your attributes as query arguments, remember to filter and sanitize user input
    $options = [
        'post_type'         => filter_var( $attributes['type'], FILTER_SANITIZE_STRING ),
        'posts_per_page'    => filter_var( $attributes['posts'], FILTER_VALIDATE_INT ),
        'tax_query'         => $tax_query
    ];
    $query = new WP_Query( $options );

    /**
     * We need to sort the loop now before we run it. If the custom attribute, term_order is an empty array or not a valid array,
     * we will sort by term name, ascending. If a valid array of term names is passed, we will sort by the order given
     *
     * There is a bug in usort causing the following error:
     * usort(): Array was modified by the user comparison function
     * @see https://bugs.php.net/bug.php?id=50688
     * This bug has yet to be fixed, when, no one knows. The only workaround is to suppress the error reporting
     * by using the @ sign before usort
     */
    @usort( $query->posts, function ( $a, $b ) use ( $taxonomy, $terms_array, $order, $orderby )
    {
        // We will use names, so the array should be names as well. Change according to needs
        $array_a = get_the_terms( $a->ID, $taxonomy )[0]->name;
        $array_b = get_the_terms( $b->ID, $taxonomy )[0]->name;

        // If the post terms are the same, orderby the value of $attributes['orderby']
        if ( $array_a != $array_b ) {   
            // If $terms_array is empty, sort by name default
            if ( !$terms_array )
                return strcasecmp( $array_a, $array_b );

            $array_flip = array_flip( $terms_array );
            return $array_flip[$array_a] - $array_flip[$array_b];
        } else {
            $orderby_param = ['ID', 'post_date', 'post_date_gmt', 'post_parent', 'post_modified', 'post_modified_gmt', 'comment_count', 'menu_order'];
            if ( in_array( $orderby, $orderby_param ) ) {
                if ( $order == 'ASC' ) {
                    return $a->$orderby - $b->$orderby; 
                } else {
                    return $b->$orderby - $a->$orderby; 
                }
            } else { 
                if ( $order == 'ASC' ) {
                    return strcasecmp( $a->$orderby, $b->$orderby );    
                } else {
                    return strcasecmp( $b->$orderby, $a->$orderby );    
                }
            }
        }
    });

    if ( $query->have_posts() ) {
        //Will hold the term name of the previous post for comparison
        $term_name_string = '';
        // Start a counter in order to set our 'section_inner clearfix' and 'section_inner_margin clearfix' divs correctly
        $counter = 0;

            while ( $query->have_posts() ) { 
                $query->the_post(); 

                // Display the term name
                global $post;
                $terms_array = get_the_terms( $post->ID, $taxonomy );
                $term_name = $terms_array[0]->name;

                /**
                 * If this $term_name_string is not $term_name, we have a lot to do like display term name,
                 * and opening and closing divs
                 */
                if ( $term_name_string != $term_name ) { 
                    // Reset our counter back to 0 to set our 'section_inner clearfix' and 'section_inner_margin clearfix' divs correctly
                    $counter = 0;
                    /**
                     * We need to close our 'section_inner clearfix' and 'section_inner_margin clearfix' divs
                     * We also need to close our previous term div if term name changes 
                     * Open our div to wrap each term in a block. We will do this in same way as our term names
                     * Also open our 'section_inner clearfix' and 'section_inner_margin clearfix' divs
                     */
                    if ( $query->current_post != 0 ) {  
                        echo '</div></div> <!--/.wrap-->'."\n"; 
                    echo '</div><!-- Close div on last post in term -->';
                    }

                    // Use the term slug here
                    echo '<div class="books-container ' . $terms_array[0]->slug . '">';

                        ?>

                            <h2 id="<?php echo $taxonomy /*I don't know what this should be, so just correct my change */ ?>" style="margin:0px 0px 20px 0px; ">
                                <?php
                                    echo $term_name;
                                ?>
                            </h2>
                        <?php 

                        echo "\n".'<div class="section_inner clearfix"><div class="section_inner_margin clearfix">'."\n"; 

                } // end $term_name_string != $term_name if condition

                /**
                 * Close our 'section_inner clearfix' and 'section_inner_margin clearfix' divs
                 * Open our 'section_inner clearfix' and 'section_inner_margin clearfix' divs on every third post
                 */
                if( $counter != 0 && $counter%3 == 0 ) {
                        echo '</div></div> <!--/.wrap-->'."\n";
                    echo "\n".'<div class="section_inner clearfix"><div class="section_inner_margin clearfix">'."\n"; 
                }

                // Set the current term name to $term_name_string for comparison
                $term_name_string = $term_name; 

                ?>

                    <div <?php post_class('vc_span4 wpb_column column_container'); ?> style="padding-bottom: 60px;">
                        <div class="wpb_wrapper">

                            <?php // Get the post thumbnail ?>
                            <?php if ( has_post_thumbnail() ) { ?>
                                <div class="wpb_single_image wpb_content_element element_from_fade element_from_fade_on">
                                    <div class="wpb_wrapper">
                                        <?php 
                                            //$large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'Book-thumbnail' );
                                            echo '<a href="' . get_permalink() . '" title="' . the_title_attribute( 'echo=0' ) . '" class="book-holder" ><span class="book-thumb">';
                                            echo get_the_post_thumbnail( $post->ID, 'book-thumbnail' ); 
                                            echo '</span></a>';
                                        ?>
                                    </div> 
                                </div>
                            <?php } ?>

                        </div>

                        <div class="wpb_text_column wpb_content_element text-align-center" style="margin: 20px 0px 0px 0px; ">

                            <div class="wpb_wrapper">
                                <h5><?php the_title(); ?></h5>
                            </div>
                            <a href="<?php the_permalink(); ?>" target="_blank" class="qbutton  small" style="margin: 20px 0px 0px 0px; "><?php _e('More Info', 'qode'); ?></a>

                        </div>

                    </div>

                <?php 
                if ( ( $query->current_post + 1 ) == $query->post_count ) { 
                    echo '</div></div> <!--/.wrap-->'."\n"; 
                echo '</div><!-- Close div on last post -->';
                }

                $counter++;
            }
            wp_reset_postdata(); 

        return ob_get_clean();
    }
}

Вот измененная версия моего кода, если вы собираетесь использовать слизни терминов вместо названий терминов

// create shortcode with parameters so that the user can define what's queried - default is to list all blog posts
add_shortcode( 'books', 'books_shortcode' );

function books_shortcode( $atts ) {
    ob_start();
    // Do not use extract(), use this syntax for your attributes
    $attributes = shortcode_atts( 
        [
            'term_order' => '', // New attribute to sort your terms in a custom order, pass a comma deliminated spaced string here. Default is term slug
            'taxonomy'   => 'booktypes',
            'type'       => 'books',
            'order'      => 'ASC',
            'orderby'    => 'title',
            'posts'      => -1,
        ], 
        $atts 
    );

    $taxonomy = filter_var( $attributes['taxonomy'], FILTER_SANITIZE_STRING );
    // Check if our taxonomy is valid to avoid errors and bugs. If invalid, return false
    if ( !taxonomy_exists( $taxonomy ) )
        return false;

    //Set the variables for sorting purposes    
    $orderby = filter_var( $attributes['orderby'], FILTER_SANITIZE_STRING );
    $order   = filter_var( $attributes['order'], FILTER_SANITIZE_STRING );

    // Convert the string of term slugs to an array
    $tax_query = [];
    if ( $attributes['term_order'] ) {
        // First we need to remove the whitespaces before and after the commas
        $no_whitespaces = preg_replace( '/\s*,\s*/', ',', filter_var( $attributes['term_order'], FILTER_SANITIZE_STRING ) );
        $terms_array = explode( ',', $no_whitespaces );

        // Build a tax_query to get posts from the passed term slugs in $attributes['term_order']
        $tax_query = [
            [
                'taxonomy'         => $taxonomy,
                'field'            => 'slug',
                'terms'            => $terms_array,
                'include_children' => false
            ],
        ];

    }

    // Pass your attributes as query arguments, remember to filter and sanitize user input
    $options = [
        'post_type'         => filter_var( $attributes['type'], FILTER_SANITIZE_STRING ),
        'posts_per_page'    => filter_var( $attributes['posts'], FILTER_VALIDATE_INT ),
        'tax_query'         => $tax_query
    ];
    $query = new WP_Query( $options );

    /**
     * We need to sort the loop now before we run it. If the custom attribute, term_order is an empty array or not a valid array,
     * we will sort by term name, ascending. If a valid array of term names is passed, we will sort by the order given
     *
     * There is a bug in usort causing the following error:
     * usort(): Array was modified by the user comparison function
     * @see https://bugs.php.net/bug.php?id=50688
     * This bug has yet to be fixed, when, no one knows. The only workaround is to suppress the error reporting
     * by using the @ sign before usort
     */
    @usort( $query->posts, function ( $a, $b ) use ( $taxonomy, $terms_array, $order, $orderby )
    {
        // We will use names, so the array should be names as well. Change according to needs
        $array_a = get_the_terms( $a->ID, $taxonomy )[0]->name;
        $array_b = get_the_terms( $b->ID, $taxonomy )[0]->name;

        // If the post terms are the same, orderby the value of $attributes['orderby']
        if ( $array_a != $array_b ) {   
            // If $terms_array is empty, sort by name default
            if ( !$terms_array )
                return strcasecmp( $array_a, $array_b );

            $array_flip = array_flip( $terms_array );
            return $array_flip[$array_a] - $array_flip[$array_b];
        } else {
            $orderby_param = ['ID', 'post_date', 'post_date_gmt', 'post_parent', 'post_modified', 'post_modified_gmt', 'comment_count', 'menu_order'];
            if ( in_array( $orderby, $orderby_param ) ) {
                if ( $order == 'ASC' ) {
                    return $a->$orderby - $b->$orderby; 
                } else {
                    return $b->$orderby - $a->$orderby; 
                }
            } else { 
                if ( $order == 'ASC' ) {
                    return strcasecmp( $a->$orderby, $b->$orderby );    
                } else {
                    return strcasecmp( $b->$orderby, $a->$orderby );    
                }
            }
        }
    });

    if ( $query->have_posts() ) {
        //Will hold the term name of the previous post for comparison
        $term_name_string = '';
        // Start a counter in order to set our 'section_inner clearfix' and 'section_inner_margin clearfix' divs correctly
        $counter = 0;

            while ( $query->have_posts() ) { 
                $query->the_post(); 

                // Display the term name
                global $post;
                $terms_array = get_the_terms( $post->ID, $taxonomy );
                $term_name = $terms_array[0]->name;

                /**
                 * If this $term_name_string is not $term_name, we have a lot to do like display term name,
                 * and opening and closing divs
                 */
                if ( $term_name_string != $term_name ) { 
                    // Reset our counter back to 0 to set our 'section_inner clearfix' and 'section_inner_margin clearfix' divs correctly
                    $counter = 0;
                    /**
                     * We need to close our 'section_inner clearfix' and 'section_inner_margin clearfix' divs
                     * We also need to close our previous term div if term name changes 
                     * Open our div to wrap each term in a block. We will do this in same way as our term names
                     * Also open our 'section_inner clearfix' and 'section_inner_margin clearfix' divs
                     */
                    if ( $query->current_post != 0 ) {  
                        echo '</div></div> <!--/.wrap-->'."\n"; 
                    echo '</div><!-- Close div on last post in term -->';
                    }

                    // Use the term slug here
                    echo '<div class="books-container ' . $terms_array[0]->slug . '">';

                        ?>

                            <h2 id="<?php echo $taxonomy /*I don't know what this should be, so just correct my change */ ?>" style="margin:0px 0px 20px 0px; ">
                                <?php
                                    echo $term_name;
                                ?>
                            </h2>
                        <?php 

                        echo "\n".'<div class="section_inner clearfix"><div class="section_inner_margin clearfix">'."\n"; 

                } // end $term_name_string != $term_name if condition

                /**
                 * Close our 'section_inner clearfix' and 'section_inner_margin clearfix' divs
                 * Open our 'section_inner clearfix' and 'section_inner_margin clearfix' divs on every third post
                 */
                if( $counter != 0 && $counter%3 == 0 ) {
                        echo '</div></div> <!--/.wrap-->'."\n";
                    echo "\n".'<div class="section_inner clearfix"><div class="section_inner_margin clearfix">'."\n"; 
                }

                // Set the current term name to $term_name_string for comparison
                $term_name_string = $term_name; 

                ?>

                    <div <?php post_class('vc_span4 wpb_column column_container'); ?> style="padding-bottom: 60px;">
                        <div class="wpb_wrapper">

                            <?php // Get the post thumbnail ?>
                            <?php if ( has_post_thumbnail() ) { ?>
                                <div class="wpb_single_image wpb_content_element element_from_fade element_from_fade_on">
                                    <div class="wpb_wrapper">
                                        <?php 
                                            //$large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'Book-thumbnail' );
                                            echo '<a href="' . get_permalink() . '" title="' . the_title_attribute( 'echo=0' ) . '" class="book-holder" ><span class="book-thumb">';
                                            echo get_the_post_thumbnail( $post->ID, 'book-thumbnail' ); 
                                            echo '</span></a>';
                                        ?>
                                    </div> 
                                </div>
                            <?php } ?>

                        </div>

                        <div class="wpb_text_column wpb_content_element text-align-center" style="margin: 20px 0px 0px 0px; ">

                            <div class="wpb_wrapper">
                                <h5><?php the_title(); ?></h5>
                            </div>
                            <a href="<?php the_permalink(); ?>" target="_blank" class="qbutton  small" style="margin: 20px 0px 0px 0px; "><?php _e('More Info', 'qode'); ?></a>

                        </div>

                    </div>

                <?php 
                if ( ( $query->current_post + 1 ) == $query->post_count ) { 
                    echo '</div></div> <!--/.wrap-->'."\n"; 
                echo '</div><!-- Close div on last post -->';
                }

                $counter++;
            }
            wp_reset_postdata(); 

        return ob_get_clean();
    }
}

ИСПОЛЬЗОВАНИЕ

Теперь вы можете использовать свой шорткод следующим образом: ( Я использовал тип записи по умолчанию post и таксономию category для целей тестирования, поэтому это объясняет мое использование атрибутов)

[books type='post' taxonomy='category' term_order="cityguides, travelguides, languageguides"]

, в котором будут отображаться сообщения из условий cityguides, travelguides, languageguides в этом конкретном порядок

РЕДАКТИРОВАТЬ

Из комментариев следует, что существует проблема с порядком сортировки сообщений в течение того же срока, когда мы сортируем только по терминам. Чтобы получить правильный порядок сортировки, лучший способ сделать это -

  • Удалите порядок сортировки из запроса, так как это действительно не имеет значения

  • Адаптируйте код в функции usort. Нам нужно отсортировать по термину и по атрибуту orderby. для этого нам нужно сравнить термины из двух сообщений, и если они совпадают, сортировать по orderby

Я обновил приведенный выше код в обоих примерах кода, чтобы отразить эти изменения. Одно большое изменение здесь - это значения, которые вы передаете orderby, потому что теперь мы будем упорядочивать по свойствам post. Вам необходимо проверить действительный WP_Post свойства и используйте их вместо значений по умолчанию , используемых с WP_Query

Так, например, если вам нужно отсортировать сообщения по названию, значение будет post_title, а не title. Если вы хотите отсортировать по дате публикации, значение будет post_date, а не date, как обычно, с WP_query

Я надеюсь, что это имеет смысл.

 3
Author: Pieter Goosen, 2015-07-09 18:49:35