Есть ли способ перечислить всех авторов, которые опубликовали видео в определенной категории, и показать их вместе, как список? - PullRequest
0 голосов
/ 15 апреля 2020

Пожалуйста, помогите мне с этим сайтом https://desarrollowebtotal.space/yoentrenoencasa/

Я использую тему goWatch из touchsize в качестве родительской темы.

Что мне нужно, это:

Когда я нажимаю на любую из категорий, перечисленных на домашней странице, например, «Йога», сайт переходит к архиву со всеми видео, созданными в этой таксономии, это не то поведение, которое мне нужно.

Я хочу, чтобы этот архив возвращал список авторов, которые опубликовали видео в этой категории и вложили в виде списка видео, связанные с этим автором в этой категории.

Возможно ли это сделать?

  // This query brings the videos within the videos_categories taxonomy that match the current slug
    $term = get_queried_object();
      $loop = new WP_Query( array(
        'post_type' => 'video',
        'posts_per_page' => 10,

        'tax_query' => array( //(array) - use taxonomy parameters (available with Version 3.1).
            'relation' => 'AND', //(string) - Possible values are 'AND' or 'OR' and is the equivalent of running a JOIN for each taxonomy
            array(
                'taxonomy' => 'videos_categories', //(string) - Taxonomy.
                'field' => 'slug', //(string) - Select taxonomy term by ('id' or 'slug')
                terms' => $term->slug, //(int/string/array) - Taxonomy term(s).
                include_children' => true, //(bool) - Whether or not to include children for hierarchical taxonomies. Defaults to true.
                'operator' => 'IN' //(string) - Operator to test. Possible values are 'IN', 'NOT IN', 'AND'.
              ),

            ),
    ) );

Это то, что я сделал до сих пор, я не знаю, как вложить списки видео, чтобы родительский элемент был автором, а дочерний - видео, связанные с этот автор

// ОБНОВЛЕНИЕ 1

     $argsA = array(
        'orderby'       => 'name', 
        'order'         => 'ASC', 
        'number'        => null,
        'optioncount'   => false, 
        'exclude_admin' => true, 
        'show_fullname' => false,
        'hide_empty'    => false,
        'echo'          => true,
        // 'feed'          => [empty string], 
        // 'feed_image'    => [empty string],
        // 'feed_type'     => [empty string],
        'style'         => 'list',
        'html'          => true,
    );

    $authors = wp_list_authors($argsA);


     // This query brings the videos within the videos_categories taxonomy that match the current slug
    $term = get_queried_object();

HTML ЧАСТЬ, ГДЕ IL OOP РЕЗУЛЬТАТЫ

  <div class="container airkit-archive-content">
        <div class="row">
            <?php if (!empty($authors)): ?>
                <?php foreach ($authors as $author): ?>

                    <?php  
                        $author_id = $author->ID;
                        $author_display_name = $author->name;

                        $query_args = array(
                          'author' => $author_id,
                          'post_type' => 'video',
                          'tax_query' => array(
                            'relation' => 'AND',
                            array(
                                'taxonomy' => 'videos_categories',
                                'field'    => 'slug',
                                'terms'    => $term->slug,
                                'include_children' => true,
                                'operator' => 'IN'

                            ),
                          ),

                       );
                    ?>

                <?php endforeach; ?> 

            <?php endif ?>


        </div>
    </div>


ВЫХОД

  • Кристиан Энтренадор
  • jb
  • Хосе Мигель
  • Йонатан Т.

Что мне нужно

  • Тренер имя
    • Видео, которые он / она опубликовал в текущей категории

ОБНОВЛЕНИЕ 2:

Выполнение запроса @Tokant / рекомендуется копировать / вставил его фрагмент, он работал, он напечатал автора, я думаю, это потому, что он единственный, кто разместил видео


      <div class="row">
            <?php $term = get_queried_object(); ?>

            <?php $authors_args = array(
                'echo'          => false,
                'orderby'       => 'name',
                'order'         => 'ASC',
            );




            $author_list = wp_list_authors($authors_args);




            if (!empty($author_list)):

                echo $author_list;

            foreach ($author_list as $author):
               $author_id = $author->ID;
               $author_display_name = $author->name;

               $query_args = array(
                  'author' => $author_id,

               );
               $the_query = new WP_Query( $query_args );
               if ( $the_query->have_posts() ) :

               while ( $the_query->have_posts() ) : $the_query->the_post();

               endwhile;
               wp_reset_postdata();
               endif;

            endforeach;
            endif; ?>


        </div>

OUPUTS T ЕГО

  • Жозе Мигель

Ответы [ 2 ]

1 голос
/ 18 апреля 2020

Доброе утро, ребята, благодаря Токанту, я смог найти решение по-своему.

Что я сделал, так это собрал макет так, чтобы иерархия была такой.

Автор - видео, опубликованные в текущей категории.

Это решение:

Вам необходимо установить плагин Buddypress для работы ключа 'orden' и добавить этот скрипт в функции. php вашей детской темы


/*Función para ordenar los autores*/

add_action('show_user_profile', 'extra_user_profile_fields');
add_action('edit_user_profile', 'extra_user_profile_fields');

function extra_user_profile_fields($user)
{ ?>

    <?php if (current_user_can('administrator')) { ?>
        <h3><?php _e("Administrar Posiciones", "blank"); ?></h3>

        <table class="form-table">
            <tr>
                <th><label for="orden"><?php _e("Modificar Orden"); ?></label></th>
                <td>
                    <input type="number" name="orden" id="orden" value="<?php echo esc_attr(get_the_author_meta('orden', $user->ID)); ?>" class="regular-text" /><br />
                    <span class="description"><?php _e("Campo solo para administradores"); ?></span>
                </td>
            </tr>
            <tr>
        </table>
    <?php } ?>
<?php }

add_action('personal_options_update', 'save_extra_user_profile_fields');
add_action('edit_user_profile_update', 'save_extra_user_profile_fields');

function save_extra_user_profile_fields($user_id)
{
    if (!current_user_can('edit_user', $user_id)) {
        return false;
    }
    update_user_meta($user_id, 'orden', $_POST['orden']);
}

  • L oop для авторов:
<?php
    // Theme's WP_Query arguments

    $airkit_video           = '';

    $figure_attributes      = array();

    $airkit_is_img          = airkit_single_option('img');
    $airkit_img_src         =wp_get_attachment_url(get_post_thumbnail_id($videos->ID));

    $airkit_video_type      = get_post_meta($videos->ID, 'video_type', true);
    $airkit_external_video  = get_post_meta($videos->ID, 'video_url', true);
    $airkit_embedded_video  = get_post_meta($videos->ID, 'video_embed', true);
    $airkit_uploaded_video  = get_post_meta($videos->ID, 'video_upload', true);

    //Arguments for users Query 
        $arg_user =  array(
            'role__in'             => ['author'],
            'post_type'            => 'video',
            'has_published_posts'  => ['video'],
            'fields'               => ['ID'],
            'meta_query' => array(
                array(
                    'relation' => 'OR',
                    array('key' => 'orden', 'value' => '0', 'compare' => '!='),
                    array('key' => 'orden', 'compare' => 'NOT EXISTS'),
                ),
            ),
            'orderby' => 'meta_value',
            'order' => 'ASC',
        );

            //var_dump($arg_user);
            $yec_args = get_users($arg_user); //We obtain the list of all the users of the site to compare with the criteria of the query, it will look for in the author role, the users that have published entries in the custom post type video and it will avoid to bring the ones that do not have entries.

            $yec_user_id  = wp_list_pluck($yec_args, 'ID');
            //print_r($yec_user_id);

        ?>
?>

Затем мы через l oop через каждого автора выводим html


   <div class="container container-todo" style="transform: none; display: flex;">
            <div class="post-details-row current-reading" style="transform: none;">

        <?php
        // Loop & retrieve el ID authors ID

        foreach ($yec_user_id as $author_id): //main FOREACH
            // We get the ID of the current author who is returning the loop
            $curauth = get_userdata($author_id);
            //var_dump($curauth->user_nicename);

            $args = array(
                'posts_per_page' => -1,
                'post_type' => 'video',
                'author' => $author_id,
                'groupby' => 'author',
                'tax_query' => array(
                    array(
                        'taxonomy' => 'videos_categories',
                        'field' => 'slug',
                        'terms' => get_queried_object()->slug,
                    ),
                ),
                'meta_key' => 'airkit_views',
                'orderby' => 'meta_value_num',
                'order' => 'DESC'

            );

            //We return the videos and count them.

            $posts = get_posts($args);
            $number_post = count($posts);

            //var_dump($number_post);

            //if this author has posts, then include his name in the list otherwise don't


            if (isset($posts) && !empty($posts)) { // MAIN IF?>


                        <div class="row" style="display: flex; align-items: center;">
                            <div class="sidebar-right col-lg-12 col-md-12 col-xs-12" style="display: flex; justify-content: center; flex-wrap: wrap;">
                                <!-- Datos del autor -->
                                <div class="tszf-author-body">
                                    <div class="item col-md-12 col-xs-12" style="text-align: center;">
                                        <div class="yec-user-image">
                                            <img src="<?php echo esc_url(get_avatar_url($author_id)); ?>" />
                                        </div>
                                        <div class="item col-xs-12">
                                            <span class="yec-authors"> <a href=" <?php echo get_option('siteurl') . '/members/' . $curauth->user_nicename . '/posts' ?>" class="post-link"> <?php echo "" . $curauth->first_name . " " . $curauth->last_name . ""; ?> </a></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="tszf-user-name">

                                    <ul class="social"><?php echo airkit_var_sanitize($social_icons, 'the_kses'); ?></ul>
                                </div>
                                <!-- Fin de datos del autor -->


                                <!-- Aquí deben ir los vídeos de ese autor -->

                                <?php $count = 0;  ?>

                                <?php foreach ($posts as $post) { ?>
                                    <?php if ($count == "4") {
                                        // Si hay vídeos no imprimas más de 2 y salte del condicional
                                        break;
                                    } else{ ?>

                                        <!-- Este es el bloque iterable -->
                                        <div class="item col-lg-4 col-md-6 col-sm-6 col-xs-12">

                                            <article class="video type-video status-publish has-post-thumbnail hentry has-lazy-placeholder airkit_view-article text-left below-image effect-always hidden-excerpt has-image" itemscope="" itemtype="http://schema.org/Article">
                                                <figure class="image-holder has-background-img lazy lazyloaded" style="background-image: url(<?php echo get_the_post_thumbnail_url($post->ID, 'full') ?>); display: block;">

                                                    <a class="post-format-link" href="<?php the_permalink(); ?>" title="<?php echo $post->post_title; ?>">

                                                        <span class="post-type"><i class="icon-play-full"></i></span>
                                                    </a>

                                                    <a href="<?php the_permalink(); ?>" class="post-link"></a>

                                                    <div class="overlay-effect ">
                                                        <a href="<?php the_permalink(); ?>" class="overlay-link darken">
                                                        </a>
                                                    </div>

                                                </figure>


                                                <header class="entry-content-below">
                                                    <div class="entry-content">
                                                        <ul class="entry-categories">
                                                            <li class="term">
                                                                <?php $slug = get_queried_object()->slug;  ?>
                                                                <a href="<?php the_permalink(); ?>"><?php echo $post->post_title; ?></a>
                                                                <!-- <a href="<?php echo $post->guid; ?>"><?php echo $slug; ?></a> -->
                                                            </li>
                                                        </ul>

                                                        <h2 class="entry-title" itemprop="name headline">
                                                            <a href="<?php the_permalink(); ?>" title="<?php echo $post->post_title; ?>"><?php echo $video->post_title; ?></a>

                                                            <div class="widget-meta">
                                                                <ul class="list-inline">
                                                                    <li class="red-comments">
                                                                        <a href="<?php echo get_permalink($post->ID) . '#comments' ?>">
                                                                            <i class="icon-comments"></i>
                                                                            <span class="comments-count">
                                                                                <?php echo airkit_var_sanitize($post->comment_count, 'the_kses') . ' '; ?>
                                                                            </span>
                                                                        </a>
                                                                    </li>

                                                                    <li class="meta-views">
                                                                        <i class="icon-views-1"></i> <?php airkit_get_views($post->ID, true); ?>
                                                                    </li>
                                                                </ul>
                                                            </div>
                                                        </h2>
                                                    </div> <!-- Aquí termina el contenido de los vídeos -->
                                                </header>

                                            </article>
                                        </div>
                                        <!--Fin del bloque iterable -->


                                    <?php $count++; } //CIERRE DEL IF DEL COUNT ?> 
                                <?php } //CIERRE FOREACH DE POST    ?>
                            </div>

                            <!-- Flecha que nos lleva al perfil del autor -->
                            <a href=" <?php echo get_option('siteurl') . '/members/' . $curauth->user_nicename . '/posts' ?>" class="post-link">

                                <span style="font-size: 3em; color: rgba(60,185,207,1);">
                                    <i class="fas fa-angle-double-right" style="margin-top:50px"></i>
                                </span>
                                <br />
                            </a>
                            <span style="color: rgba(60,185,207,1);"> (<?php echo $number_post; ?>) <i class="fas fa-video"></i> </span>
                            </div>




            <?php } // END of MAIN IF   ?>



        <?php endforeach; //END OF MAIN FOREACH ?>
0 голосов
/ 16 апреля 2020

Вы можете сделать WP_Query для всех авторов. В l oop для каждого автора вы сначала получаете идентификатор автора, а затем создаете WP_Query для типа записи «видео», как вы уже сделали, но добавляете идентификатор автора в $ args, например:

$authors_args = array(
    'echo'          => false,
    'orderby'       => 'name',
    'order'         => 'ASC',
);
$authors = wp_list_authors($args);
if (!empty($authors)):
foreach ($authors as $author):
   $author_id = $author->ID;
   $author_display_name = $author->name;

   $query_args = array(
      'author' => $author_id,
      [your args]
   );
   $the_query = new WP_Query( $query_args );
   if ( $the_query->have_posts() ) :
   [output author name]
   while ( $the_query->have_posts() ) : $the_query->the_post();
      [output post/video]
   endwhile;
   wp_reset_postdata();
   endif;

endforeach;
endif;
...