Как отобразить термин таксономии вместе с заголовком сообщения типа сообщения? - PullRequest
0 голосов
/ 14 апреля 2020

Я хотел бы отобразить термин таксономии сообщения типа сообщения помимо заголовка сообщения типа сообщения, разделенного текстовой строкой "in".

Существует две проблемы:

  1. вместо термина отображается только «массив»
  2. Я не знаю, как правильно кодировать текстовую строку «in» между термином и заголовком (они должны быть в одной строке)

Вот (неправильный) код, о котором идет речь:

$output .= '<div>' . get_the_title() . '</div>'; in $output .= '<div>' . wp_get_post_terms( $post_id, $taxonomy = 'itemscategories') . '</div>';

Встроенный в этот шорткод:

function myprefix_custom_grid_shortcode( $atts ) {

    // Parse your shortcode settings with it's defaults
    $atts = shortcode_atts( array(

        'posts_per_page' => '-1',
        'term'           => ''
    ), $atts, 'myprefix_custom_grid' );
$user_id = userpro_get_view_user( get_query_var('up_username') );
    // Extract shortcode atributes
    extract( $atts );

    // Define output var
    $output = '';



    // Define query
    $query_args = array(
    'author'=> $user_id,
        'post_type'      => 'items', // Change this to the type of post you want to show
        'posts_per_page' => $posts_per_page,
    );

    // Query by term if defined
    if ( $term ) {

        $query_args['tax_query'] = array(
            array(
                'taxonomy' => 'category',
                'field'    => 'ID',
                'terms'    => $term,

            ),
        );

    }

    // Query posts
    $custom_query = new WP_Query( $query_args );

    // Add content if we found posts via our query
    if ( $custom_query->have_posts() ) {

        // Open div wrapper around loop
        $output .= '<div>';

        // Loop through posts
        while ( $custom_query->have_posts() ) {

            // Sets up post data so you can use functions like get_the_title(), get_permalink(), etc
            $custom_query->the_post();

            // This is the output for your entry so what you want to do for each post.
            $output .= '<div>' . get_the_title() . '</div>'; in $output .= '<div>' . wp_get_post_terms( $post_id, $taxonomy = 'itemscategories') . '</div>';

        }

        // Close div wrapper around loop
        $output .= '</div>';

        // Restore data
        wp_reset_postdata();

    }

    // Return your shortcode output
    return $output;

}
add_shortcode( 'myprefix_custom_grid', 'myprefix_custom_grid_shortcode' );

1 Ответ

0 голосов
/ 15 апреля 2020

Функция wp_get_post_terms по умолчанию возвращает массив, поэтому, если вы хотите отобразить имя первого термина, вы можете сделать что-то вроде этого:

// This is the output for your entry so what you want to do for each post.
$terms = wp_get_post_terms( $post_id, 'itemscategories' );
if ( $terms && ! is_wp_error( $terms ) ) {
    $output .= '<div>' . esc_html( get_the_title() ) . ' ' . esc_html__( 'Posted in:', 'text_domain' ) . ' ' . esc_html( $terms[0]->name ) . '</div>';
}

Или вместо этого вы можете использовать альтернативную функцию - https://developer.wordpress.org/reference/functions/get_the_term_list/

// This is the output for your entry so what you want to do for each post.
$output .= '<div>' . esc_html( get_the_title() ) . get_the_term_list( $post_id, 'itemscategories', 'Posted in: ', ', ' ) . '</div>';

Эта функция отображает список всех терминов, относящихся к сообщению, со ссылками на архивы терминов. Если вы хотите удалить архивные ссылки, вы можете заключить get_the_terms_list в функцию strip_tags.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...