шорткод получить все сообщения [показывает проблемы категорий сообщений] - PullRequest
0 голосов
/ 04 мая 2020

Я пытаюсь создать шорткод, чтобы получить все сообщения, перейдя по этой ссылке

Мой код шорткода вставлен в функции дочерней темы. php file.:-

function myprefix_custom_grid_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'posts_per_page' => '-1',
        'term'           => '',
    ), $atts, 'myprefix_custom_grid' );
    extract( $atts );
    $output = '';
    $query_args = array(
        'post_type'      => 'post', // Change this to the type of post you want to show
        'posts_per_page' => $posts_per_page,
    );
    if ( $term ) {
        $query_args['tax_query'] = array(
            array(
                'taxonomy' => 'category',
                'field'    => 'ID',
                'terms'    => $term,
            ),
        );
    }
    // Query posts
    $custom_query = new WP_Query( $query_args );
    if ( $custom_query->have_posts() ) {
        $output .= '<ul class="yj-trainingcamp-list clearfix">';
        while ( $custom_query->have_posts() ) {
            $custom_query->the_post();
            $categories = get_the_category();
            $separator = ' ';
            $output_cats = '';
            if($categories){
                foreach($categories as $category) {
                    $output_cats .= '<a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator;
                }
            }

            $output .= '<li class="yj-trainingcamp-item">
                <a href="' . get_permalink() . '" title="' . get_the_title() . '" class="trainingcamp-atom-wrap" target="_blank">
                    <div class="cover-img-zone">
                        <div class="el-image cover-img"><img src="' .get_the_post_thumbnail_url($post->ID, 'full'). '" alt="" class="el-image__inner" style="object-fit: cover;"></div></div><div class="infos"><div class="camp-info"><div class="camp-name"><span class="camp-num">第10期</span>' . get_the_title() . '</div>
                        <div class="nums"><div class="sale-count">' .get_the_excerpt(). ' ' . trim($output_cats, $separator) . ' </div>
                            </div>
                        </div>
                        <div class="teacher-info">
                            <div class="teacher-img-zone">
                                <div class="el-image teacher-img">' . get_avatar( get_the_author_meta('user_email') , 32 ) . '
                                </div>
                            </div>
                            <div class="teacher-name">作者: ' .get_the_author(). ' | ' .get_the_modified_time('M j, Y'). '</div>
                        </div>
                    </div>
                </a>
            </li>';
        }
        $output .= '</ul>';
        wp_reset_postdata();
    }
    return $output;
}
add_shortcode( 'myprefix_custom_grid', 'myprefix_custom_grid_shortcode' );

Вот проблема , показывающая несколько div

хочу отображать название категории и ссылку на категорию (foreach) в каждом сообщении, но не работает ... Ниже приведена часть Я сомневаюсь ...

$categories = get_the_category();
$separator = ' ';
$output_cats = '';
if($categories){
    foreach($categories as $category) {
        $output_cats .= '<a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator;
    }
}

1 Ответ

0 голосов
/ 04 мая 2020

сейчас не совсем уверен, потому что я не могу отладить его и не могу прочитать текст на картинке, но, как описано в wordpress документации , вы можете установить идентификатор записи для функции :

get_the_category( int $id = false )

Небольшой пример со страницы: Получить категории сообщений извне L oop

Поэтому я бы предложил добавить идентификатор сообщения для get_the_category, например так:

$categories = get_the_category(get_the_ID());
$separator = ' ';
$output_cats = '';
if($categories){
    foreach($categories as $category) {
        $output_cats .= '<a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator;
    }
}

В противном случае, я думаю, foreach l oop добавляет все категории (имена и ссылки) к каждому сообщению, потому что вы все опубликованные категории.

...