Suporte » Plugins » Ordenar posts dúvida

  • Resolvido leislaa

    (@leislaa)


    As postagens do site do meu cliente não são separadas por categorias, são todos cadastrados ‘sem categoria’.

    Ele utiliza para postar notícias.

    É possível exibir as notícias no site filtrando pela ordem da postagem?

    Existem 3 áreas na página inicial do site onde as notícias serão exibidas, eu gostaria de organizar a exibição da seguinte maneira, exemplo:

    – Notícias em Destaque (exibir 4 últimos posts)
    – Notícias Recentes (exibir do 5º ao 8º post)
    – Outras (exibir 9º em diante)

    O tema que estou usando é o Colormag
    http://demo.themegrill.com/colormag/

    No slider ficariam as 4 últimas. Ao lado a 5ª, 6ª, 7ª e 8ª postagem.
    E abaixo 9ª em diante.

    Existe alguma função que seja possível organizar desta forma?
    Se possível, por gentileza mostrar um código modelo.

    • Este tópico foi modificado 6 anos, 5 meses atrás por leislaa.
Visualizando 2 respostas - 1 até 2 (de um total de 2)
  • Moderador Felipe Elia

    (@felipeelia)

    Oi @leislaa,

    Você vai precisar alterar bastante o front-page.php do seu tema, por isso te recomendo, se ainda não fez, criar um tema filho. Assim você não perderá atualizações do Colormag quando elas forem liberadas.

    Pelo que vi, o tema trabalha com áreas para widgets, mas será mais fácil abandonar essa abordagem retirando as áreas para os widgets e substituindo-as por chamadas a WP_Query. Outro caminho é criar seus próprios widgets, mas é um pouco mais difícil (e dependerá do WP_Query da mesma forma). Para a quantidade de posts que deverão ser “pulados” você vai precisar dos parâmetros de paginaçãoparâmetros de ordenação te ajudem.

    Só para você ter uma ideia, para os posts do lado do slider você teria que trocar no front-page.php:

    <div class="widget_beside_slider">
       <?php
       if( is_active_sidebar( 'colormag_front_page_area_beside_slider' ) ) {
          if ( !dynamic_sidebar( 'colormag_front_page_area_beside_slider' ) ):
          endif;
       }
       ?>
    </div>

    por

    <div class="widget_beside_slider">
    	<?php
    	   $get_featured_posts = new WP_Query( array(
    	      'posts_per_page'        => 4, // exibe quatro posts
    	      'post_type'             => 'post',
    	      'ignore_sticky_posts'   => true,
    	      'offset'             	  => 4, // pula os 4 primeiros posts
    	   ) );
    
    	   if ($get_featured_posts->have_posts()) {
    	   	// copie aqui todo o while do arquivo inc/widgets/widgets.php linha 409
    	   }
    	?>
    </div>

    Obviamente não é o código pronto, mas é um caminho para que você possa entregar o produto para seu cliente.

    Se não houver mais nenhuma dúvida sobre esse assunto não esqueça de marcar o tópico como “resolvido”, ok?

    Criador do tópico leislaa

    (@leislaa)

    Obrigada.

    Eu resolvi de outra forma, alterando o arquivo widgets.php. Criando novos widgets, “Ao Lado do Slider” e “Abaixo do Slider”.

    Acredito que ao atualizar vou perder essas informações, mas tenho uma cópia do código de qualquer maneira. Se eu colocar o arquivo modificado em um tema filho funcionará corretamente?

    Se mais alguém teve essa dificuldade segue abaixo o código que eu inclui no meu arquivo widgets.php:

    
       register_widget( "colormag_featured_posts_widget_abaixo_slider" );
       register_widget( "colormag_highlighted_posts_widget_lado_slider" );
    
    //Exibe da 5ª a 8ª postagem da categoria escolhida
    class colormag_highlighted_posts_widget_lado_slider extends WP_Widget {
    
       function __construct() {
          $widget_ops = array( 'classname' => 'widget_highlighted_posts widget_featured_meta', 'description' => __( 'Ideal para utilizar ao lado do Slider. Exibe da 5ª a 8ª postagem mais recente.', 'colormag') );
          $control_ops = array( 'width' => 200, 'height' =>250 );
          parent::__construct( false,$name= __( 'TG: Ao lado do Slider', 'colormag' ),$widget_ops);
       }
    
       function form( $instance ) {
          $tg_defaults['number'] = 4;
          $tg_defaults['type'] = 'latest';
          $tg_defaults['category'] = '';
          $instance = wp_parse_args( (array) $instance, $tg_defaults );
          $number = $instance['number'];
          $type = $instance['type'];
          $category = $instance['category'];
          ?>
          <p>
             <label for="<?php echo $this->get_field_id('number'); ?>"><?php _e( 'Number of posts to display:', 'colormag' ); ?></label>
             <input id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="text" value="<?php echo $number; ?>" size="3" />
          </p>
    
          <p><input type="radio" <?php checked($type, 'latest') ?> id="<?php echo $this->get_field_id( 'type' ); ?>" name="<?php echo $this->get_field_name( 'type' ); ?>" value="latest"/><?php _e( 'Show latest Posts', 'colormag' );?><br />
           <input type="radio" <?php checked($type,'category') ?> id="<?php echo $this->get_field_id( 'type' ); ?>" name="<?php echo $this->get_field_name( 'type' ); ?>" value="category"/><?php _e( 'Show posts from a category', 'colormag' );?><br /></p>
    
          <p>
             <label for="<?php echo $this->get_field_id( 'category' ); ?>"><?php _e( 'Select category', 'colormag' ); ?>:</label>
             <?php wp_dropdown_categories( array( 'show_option_none' =>' ','name' => $this->get_field_name( 'category' ), 'selected' => $category ) ); ?>
          </p>
          <?php
       }
    
       function update( $new_instance, $old_instance ) {
          $instance = $old_instance;
          $instance[ 'number' ] = absint( $new_instance[ 'number' ] );
          $instance[ 'type' ] = $new_instance[ 'type' ];
          $instance[ 'category' ] = $new_instance[ 'category' ];
    
          return $instance;
       }
    
       function widget( $args, $instance ) {
          extract( $args );
          extract( $instance );
    
          global $post;
          $number = empty( $instance[ 'number' ] ) ? 4 : $instance[ 'number' ];
          $type = isset( $instance[ 'type' ] ) ? $instance[ 'type' ] : 'latest' ;
          $category = isset( $instance[ 'category' ] ) ? $instance[ 'category' ] : '';
    
          if( $type == 'latest' ) {
             $get_featured_posts = new WP_Query( array(
                'posts_per_page'        => $number,
                'post_type'             => 'post',
                'ignore_sticky_posts'   => true
             ) );
          }
          else {
             $get_featured_posts = new WP_Query( array(
                'posts_per_page'        => 4,
                'post_type'             => 'post',
                'category__in'          => $category,
                'offset'                => 4
             ) );
          }
          echo $before_widget;
          ?>
          <div class="widget_highlighted_post_area">
          <?php $featured = 'colormag-highlighted-post'; ?>
             <?php
             $i=1;
             while( $get_featured_posts->have_posts() ):$get_featured_posts->the_post();
                ?>
                <div class="single-article">
                   <?php
                   if( has_post_thumbnail() ) {
                      $image = '';
                      $title_attribute = get_the_title( $post->ID );
                      $image .= '<figure class="highlights-featured-image">';
                      $image .= '<a href="' . get_permalink() . '" title="'.the_title( '', '', false ).'">';
                      $image .= get_the_post_thumbnail( $post->ID, $featured, array( 'title' => esc_attr( $title_attribute ), 'alt' => esc_attr( $title_attribute ) ) ).'</a>';
                      $image .= '</figure>';
                      echo $image;
                   } else { ?>
                      <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
                         <img src="<?php echo get_template_directory_uri(); ?>/img/highlights-featured-image.png">
                      </a>
                   <?php }
                   ?>
                   <div class="article-content">
                      <?php colormag_colored_category(); ?>
                      <h3 class="entry-title">
                         <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute();?>"><?php the_title(); ?></a>
                      </h3>
                      <div class="below-entry-meta">
                         <?php
                            $time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time>';
                            $time_string = sprintf( $time_string,
                               esc_attr( get_the_date( 'c' ) ),
                               esc_html( get_the_date() )
                            );
                            printf( __( '<span class="posted-on"><a href="%1$s" title="%2$s" rel="bookmark"><i class="fa fa-calendar-o"></i> %3$s</a></span>', 'colormag' ),
                               esc_url( get_permalink() ),
                               esc_attr( get_the_time() ),
                               $time_string
                            );
                         ?>
                         <span class="byline"><span class="author vcard"><i class="fa fa-user"></i><a class="url fn n" href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>" title="<?php echo get_the_author(); ?>"><?php echo esc_html( get_the_author() ); ?></a></span></span>
                         <span class="comments"><i class="fa fa-comment"></i><?php comments_popup_link( '0', '1', '%' );?></span>
                      </div>
                   </div>
    
                </div>
             <?php
                $i++;
             endwhile;
             // Reset Post Data
             wp_reset_query();
             ?>
          </div>
          <?php echo $after_widget;
          }
    }
    
    //Exibe a postagem 9ª em diante da categoria escolhida
    class colormag_featured_posts_widget_abaixo_slider extends WP_Widget {
    
       function __construct() {
          $widget_ops = array( 'classname' => 'widget_featured_posts widget_featured_meta', 'description' =>__( 'Exibe postagens abaixo do slider, a partir da 9ª postagem.' , 'colormag') );
          $control_ops = array( 'width' => 200, 'height' =>250 );
          parent::__construct( false,$name= __( 'TG: Notícias abaixo do slider', 'colormag' ),$widget_ops);
       }
    
       function form( $instance ) {
          $tg_defaults['title'] = '';
          $tg_defaults['text'] = '';
          $tg_defaults['number'] = 4;
          $tg_defaults['type'] = 'latest';
          $tg_defaults['category'] = '';
          $instance = wp_parse_args( (array) $instance, $tg_defaults );
          $title = esc_attr( $instance[ 'title' ] );
          $text = esc_textarea($instance['text']);
          $number = $instance['number'];
          $type = $instance['type'];
          $category = $instance['category'];
          ?>
          <p><?php _e( 'Layout will be as below:', 'colormag' ) ?></p>
          <div style="text-align: center;"><img src="<?php echo get_template_directory_uri() . '/img/style-1.jpg'?>"></div>
          <p>
             <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e( 'Title:', 'colormag' ); ?></label>
             <input id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
          </p>
          <?php _e( 'Description','colormag' ); ?>
          <textarea class="widefat" rows="5" cols="20" id="<?php echo $this->get_field_id('text'); ?>" name="<?php echo $this->get_field_name('text'); ?>"><?php echo $text; ?></textarea>
          <p>
             <label for="<?php echo $this->get_field_id('number'); ?>"><?php _e( 'Number of posts to display:', 'colormag' ); ?></label>
             <input id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="text" value="<?php echo $number; ?>" size="3" />
          </p>
    
          <p><input type="radio" <?php checked($type, 'latest') ?> id="<?php echo $this->get_field_id( 'type' ); ?>" name="<?php echo $this->get_field_name( 'type' ); ?>" value="latest"/><?php _e( 'Show latest Posts', 'colormag' );?><br />
           <input type="radio" <?php checked($type,'category') ?> id="<?php echo $this->get_field_id( 'type' ); ?>" name="<?php echo $this->get_field_name( 'type' ); ?>" value="category"/><?php _e( 'Show posts from a category', 'colormag' );?><br /></p>
    
          <p>
             <label for="<?php echo $this->get_field_id( 'category' ); ?>"><?php _e( 'Select category', 'colormag' ); ?>:</label>
             <?php wp_dropdown_categories( array( 'show_option_none' =>' ','name' => $this->get_field_name( 'category' ), 'selected' => $category ) ); ?>
          </p>
          <?php
       }
    
       function update( $new_instance, $old_instance ) {
          $instance = $old_instance;
          $instance[ 'title' ] = strip_tags( $new_instance[ 'title' ] );
          if ( current_user_can('unfiltered_html') )
             $instance['text'] =  $new_instance['text'];
          else
             $instance['text'] = stripslashes( wp_filter_post_kses( addslashes($new_instance['text']) ) );
          $instance[ 'number' ] = absint( $new_instance[ 'number' ] );
          $instance[ 'type' ] = $new_instance[ 'type' ];
          $instance[ 'category' ] = $new_instance[ 'category' ];
    
          return $instance;
       }
    
       function widget( $args, $instance ) {
          extract( $args );
          extract( $instance );
    
          global $post;
          $title = isset( $instance[ 'title' ] ) ? $instance[ 'title' ] : '';
          $text = isset( $instance[ 'text' ] ) ? $instance[ 'text' ] : '';
          $number = empty( $instance[ 'number' ] ) ? 4 : $instance[ 'number' ];
          $type = isset( $instance[ 'type' ] ) ? $instance[ 'type' ] : 'latest' ;
          $category = isset( $instance[ 'category' ] ) ? $instance[ 'category' ] : '';
    
          if( $type == 'latest' ) {
             $get_featured_posts = new WP_Query( array(
                'posts_per_page'        => $number,
                'post_type'             => 'post',
                'ignore_sticky_posts'   => true
             ) );
          }
          else {
             $get_featured_posts = new WP_Query( array(
                'posts_per_page'        => $number,
                'post_type'             => 'post',
                'category__in'          => $category,
                'offset'                => 8
             ) );
          }
          echo $before_widget;
          ?>
          <?php
             if ( $type != 'latest' ) {
                $border_color = 'style="border-bottom-color:' . colormag_category_color($category) . ';"';
                $title_color = 'style="background-color:' . colormag_category_color($category) . ';"';
             } else {
                $border_color = '';
                $title_color = '';
             }
             if ( !empty( $title ) ) { echo '<h3 class="widget-title" '. $border_color .'><span ' . $title_color .'>'. esc_html( $title ) .'</span></h3>'; }
             if( !empty( $text ) ) { ?> <p> <?php echo esc_textarea( $text ); ?> </p> <?php } ?>
             <?php
             $i=1;
             while( $get_featured_posts->have_posts() ):$get_featured_posts->the_post();
                ?>
                <?php if( $i == 1 ) { $featured = 'colormag-featured-post-medium'; } else { $featured = 'colormag-featured-post-small'; } ?>
                <?php if( $i == 1 ) { echo '<div class="first-post">'; } elseif ( $i == 2 ) { echo '<div class="following-post">'; } ?>
                   <div class="single-article clearfix">
                      <?php
                      if( has_post_thumbnail() ) {
                         $image = '';
                         $title_attribute = get_the_title( $post->ID );
                         $image .= '<figure>';
                         $image .= '<a href="' . get_permalink() . '" title="'.the_title( '', '', false ).'">';
                         $image .= get_the_post_thumbnail( $post->ID, $featured, array( 'title' => esc_attr( $title_attribute ), 'alt' => esc_attr( $title_attribute ) ) ).'</a>';
                         $image .= '</figure>';
                         echo $image;
                      }
                      ?>
                      <div class="article-content">
                         <?php colormag_colored_category(); ?>
                         <h3 class="entry-title">
                            <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute();?>"><?php the_title(); ?></a>
                         </h3>
                         <div class="below-entry-meta">
                            <?php
                               $time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time>';
                               $time_string = sprintf( $time_string,
                                  esc_attr( get_the_date( 'c' ) ),
                                  esc_html( get_the_date() )
                               );
                               printf( __( '<span class="posted-on"><a href="%1$s" title="%2$s" rel="bookmark"><i class="fa fa-calendar-o"></i> %3$s</a></span>', 'colormag' ),
                                  esc_url( get_permalink() ),
                                  esc_attr( get_the_time() ),
                                  $time_string
                               );
                            ?>
                            <span class="byline"><span class="author vcard"><i class="fa fa-user"></i><a class="url fn n" href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>" title="<?php echo get_the_author(); ?>"><?php echo esc_html( get_the_author() ); ?></a></span></span>
                            <span class="comments"><i class="fa fa-comment"></i><?php comments_popup_link( '0', '1', '%' );?></span>
                         </div>
                         <?php if( $i == 1 ) { ?>
                         <div class="entry-content">
                            <?php the_excerpt(); ?>
                         </div>
                         <?php } ?>
                      </div>
    
                   </div>
                <?php if( $i == 1 ) { echo '</div>'; } ?>
             <?php
                $i++;
             endwhile;
             if ( $i > 2 ) { echo '</div>'; }
             // Reset Post Data
             wp_reset_query();
             ?>
          <!-- </div> -->
          <?php echo $after_widget;
          }
    }
    
Visualizando 2 respostas - 1 até 2 (de um total de 2)
  • O tópico ‘Ordenar posts dúvida’ está fechado para novas respostas.