A
A
Andrey2016-01-18 10:57:43
WordPress
Andrey, 2016-01-18 10:57:43

Making the first post from a given wordpress category?

It is very necessary to make the design of the first post from a certain wordpress heading. So that the first entry outputs php the_content, and the rest the_excerpt.
I found on the net the code for outputting a cycle of posts from a specific category:

<?php
if ( have_posts() ) : // если имеются записи в блоге.
  query_posts('cat=55,66');   // указываем ID рубрик, которые необходимо вывести.
  while (have_posts()) : the_post();  // запускаем цикл обхода материалов блога
?>
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<?php the_content();
endwhile;  // завершаем цикл.
endif;
/* Сбрасываем настройки цикла. Если ниже по коду будет идти еще один цикл, чтобы не было сбоя. */
wp_reset_query();                
?>

Then I found the registration code for the first post. To do this, add $postCount
<?php $postCount = 0; //счетчик
if (have_posts()) : while (have_posts()) : the_post();
$postCount++ ; //увеличиваем счетчик
if ($postCount == '1') { //первая запись
<h2 class="first"></h2>
<?php } ELSE {  ?>//не первая запись
<h2 class="article_name"></h2>
<?php } ?>
//код вывода записей
//вставляем разделитель
<?php if ($postCount !== sizeof($posts)) { ?>
<div class="separator"></div>
<?php } ; endwhile; ?>

Task: add the $postCount parameter to the first code from the second code, but, alas, I don’t have enough knowledge how to do it correctly. Tell me, please, who knows.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mr Crabbz, 2016-01-18
@dyba

<?php
/**
 * The template for displaying all pages.
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site may use a
 * different template.
 *
 * @link https://codex.wordpress.org/Template_Hierarchy
 *
 * @package test
 */

get_header(); ?>

  <div id="primary" class="content-area">
    <main id="main" class="site-main" role="main">

      <?php
      while ( have_posts() ) : the_post();

        the_title(); //Это тайтл самой страницы (если нужен)
        the_content(); // это контент страницы, заполенный непосредственно в этой странице в админке (если нужен)

        // далее комменты (если надо)
        if ( comments_open() || get_comments_number() ) :
          comments_template();
        endif;

      endwhile; // End of the loop.
      ?>

      <!-- Вот тут уже отдельным лупом - вывод нужных вам постов -->

      <?php
        // Запускаем отдельный цикл (loop) независимо от контента главной
        $args = array (
          'post_type'              => array( 'post' ),
          'post_status'            => array( 'publish' ),
          'category__in' 			 => array(55,66) // тут category__in - не ошибка. Два андерскора между словами.
        );

        // The Query
        $curstom_query = new WP_Query( $args );

        // The Loop
        if ( $curstom_query->have_posts() ) {
          $postCount = 0;
          while ( $curstom_query->have_posts() ) {
            $curstom_query->the_post();
            // тут делаем что нам надо с постами 
            $postCount++;
            ?>
            
            <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
            <?php 
            if($postCount==1){
              the_content();
            }
            else {
              the_excerpt();
            }

          }
        } else {
          // Тут выводим сообщение о том, что таких постов не найдено (если они реально не найдены)
          ?>
          <h3 class="not-found">Извините. Таких постов не найдено</h3>
          <?php
        }

        // убиваем кастомный луп
        wp_reset_postdata();
      ?>

    </main><!-- #main -->
  </div><!-- #primary -->

<?php
get_sidebar();
get_footer();

A
Andrey, 2016-01-18
@dyba

If I still use it like this, is that correct?

if($postCount==1){
  <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
  <div class="first">
  the_content();
  </div>
}
else {
  <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
  <div class="other">
  the_excerpt();
  </div>
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question