WordPress как на ладони
Очень Удобный и Быстрый Хостинг для сайтов на WordPress. Пользуюсь сам и вам рекомендую!

Виджет Последних Записей для страницы с выводом в две колонки

Для бесплатного варианта темы Spacious создал виджет последних записей для вывода на страницу.

CSS, HTML и прочее (на что хватило понимания и фантазии) скопировал из кода демо версии Spacious Pro в файлы дочерней темы бесплатного варианта темы Spacious,

в functions.php прописал код виджета http://pastie.org/private/1d1ldiuffqpa8ru8kdhog ,

не могу найти как включить чередование классов "tg-one-half" и "tg-one-half tg-one-half-last" для "div", что бы посты выводились в две колонки по схеме

1 2
3 4
и т.д.

с пхп работаю на интуиции и методе тыка

0
Гость
7.3 года назад
  • 0
    PHouse6 poweredhouse.ru

    В css

    .tg-one-half {
    	float: left;
    	width: 48.7684729%;
    	margin: 0 2.46305419% 0 0;
    	padding: 0px 0px 30px;

    измените margin: 0 2.46305419% 0 0; вместо 2.46305419% пропишите к примеру 5px. Это значит отступ от правого края. Сейчас он у вас порядка 30px(2.46305419%) поэтому две записи не вмещаются в блок.

    Либо так:

    .tg-one-half {
    	float: left;
    	width: 48%;
    	margin: 0 1% 0 0;
    	padding: 0px 0px 30px;
    earlnik 7.3 года назад

    Это не то решение, так как шаблон адаптивный и все настройки CSS уже прописаны как надо, при таком решении адаптация не работает

    Необходимо решение ресурсами PHP

    Сейчас код, который выводит виджет выглядит вот так

    <section id="featured_posts-7" class="widget widget_featured_posts clearfix">
    <h3 class="widget-title">Highlighted features of our theme</h3>
    <p>There are plenty more features hidden inside and we are determined to constantly add new features.</p>
    <div class="tg-one-half">...</div>
    <div class="tg-one-half">...</div>
    <div class="tg-one-half">...</div>
    <div class="tg-one-half">...</div>
    </section>

    а нужно, что бы выводился вот так

    <section id="featured_posts-7" class="widget widget_featured_posts clearfix">
    <h3 class="widget-title">Highlighted features of our theme</h3>
    <p>There are plenty more features hidden inside and we are determined to constantly add new features.</p>
    <div class="tg-one-half">...</div>
    <div class="tg-one-half tg-one-half-last">...</div>
    <div class="tg-one-half">...</div>
    <div class="tg-one-half tg-one-half-last">...</div>
    </section>

    тоесть в коде виджета не хватает функции для такого чередования class для div (код PHP виджета здесь http://pastie.org/private/1d1ldiuffqpa8ru8kdhog )

    Комментировать
  • 0
    Kama9616

    Вот измененный код

    <?php
    
    class featured_posts_widget extends WP_Widget {
    
    	/*
    	 * создание виджета
    	 */
    	function __construct() {
    		parent::__construct(
    			'featured_posts',
    			'Популярные посты', // заголовок виджета
    			array( 'description' => 'Позволяет вывести посты, отсортированные по количеству комментариев в них.' ) // описание
    		);
    	}
    
    	/*
    	 * фронтэнд виджета
    	 */
    	public function widget( $args, $instance ) {
    		$title = apply_filters( 'widget_title', $instance['title'] ); // к заголовку применяем фильтр (необязательно)
    		 $text = apply_filters( 'widget_text', $instance['text'] );
    		$posts_per_page = $instance['posts_per_page'];
    
    		echo $args['before_widget'];
    
    		if ( ! empty( $title ) )
    			echo $args['before_title'] . $title . $args['after_title'];
    		if ( ! empty( $text ) )
    			?><p><?php echo esc_textarea( $text ); ?></p><?php
    
    		$i=1;
    		$q = new WP_Query("posts_per_page=$posts_per_page");
    		if( $q->have_posts() ):
    			while( $q->have_posts() ): $q->the_post();
    
    			$alt_class = ($i++%2 ? ' tg-one-half-last' : '');
    
    			?><div class="tg-one-half<?=$alt_class?>"><?php
    				?><header class="entry-header">
    					<h2 class="entry-title">
    						<a href="<?php the_permalink() ?>" title="<?php the_title_attribute();?>"><?php the_title() ?></a>
    					</h2>
    				 </header><?php
    				 ?><figure class="post-featured-image">
    						<?php
    						if ( has_post_thumbnail( ) ) {
    							echo '<a title="'.get_the_title().'" href="'.get_permalink().'">'.get_the_post_thumbnail( $post->ID,'featured-blog-medium').'</a>';
    						}
    						?>
    					</figure><?php
    
    	?><div class="entry-content clearfix">
    		<?php
    			the_excerpt();
    		?>
    	</div><?php
    
       if ( 'post' == get_post_type() ) :
    	  echo '<footer class="entry-meta-bar clearfix">';
    	  echo '<div class="entry-meta clearfix">';
    	  ?>
    
    	  <span class="by-author author vcard"><a class="url fn n" href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) ); ?>"><?php the_author(); ?></a></span>
    
    	  <?php
    	  $time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time>';
    	  if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) {
    		 $time_string .= '<time class="updated" datetime="%3$s">%4$s</time>';
    	  }
    	  $time_string = sprintf( $time_string,
    		 esc_attr( get_the_date( 'c' ) ),
    		 esc_html( get_the_date() ),
    		 esc_attr( get_the_modified_date( 'c' ) ),
    		 esc_html( get_the_modified_date() )
    	  );
    	  printf( __( '<span class="date"><a href="%1$s" title="%2$s" rel="bookmark">%3$s</a></span>', 'spacious' ),
    		 esc_url( get_permalink() ),
    		 esc_attr( get_the_time() ),
    		 $time_string
    	  ); ?>
    
    	  <?php if( has_category() ) { ?>
    		 <span class="category"><?php the_category(', '); ?></span>
    	  <?php } ?>
    
    	  <?php if ( comments_open() ) { ?>
    		 <span class="comments"><?php comments_popup_link( __( 'No Comments', 'spacious' ), __( '1 Comment', 'spacious' ), __( '% Comments', 'spacious' ), '', __( 'Comments Off', 'spacious' ) ); ?></span>
    	  <?php } ?>
    
    	  <?php edit_post_link( __( 'Edit', 'spacious' ), '<span class="edit-link">', '</span>' ); ?>
    
    	  <?php if ( ( spacious_options( 'spacious_archive_display_type', 'blog_large' ) != 'blog_full_content' ) && !is_single() ) { ?>
    		 <span class="read-more-link"><a class="read-more" href="<?php the_permalink(); ?>"><?php _e( 'Read more', 'spacious' ); ?></a></span>
    	  <?php } ?>
    
    	  <?php
    	  echo '</div>';
    	  echo '</footer>';
       endif;
    			?></div><?php
    
    			endwhile;
    		endif;
    		wp_reset_postdata();
    
    		echo $args['after_widget'];
    	}
    
    	/*
    	 * бэкэнд виджета
    	 */
    	public function form( $instance ) {
    		if ( isset( $instance[ 'title' ] ) ) {
    			$title = $instance[ 'title' ];
    		}
    		if ( isset( $instance[ 'text' ] ) ) {
    			$text = $instance[ 'text' ];
    		}
    		if ( isset( $instance[ 'posts_per_page' ] ) ) {
    			$posts_per_page = $instance[ 'posts_per_page' ];
    		}
    		?>
    		<p>
    			<label for="<?php echo $this->get_field_id( 'title' ); ?>">Заголовок</label>
    			<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
    		</p>
    		<?php _e( 'Description','spacious' ); ?>
    		<textarea class="widefat" rows="10" 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( 'posts_per_page' ); ?>">Количество постов:</label>
    			<input id="<?php echo $this->get_field_id( 'posts_per_page' ); ?>" name="<?php echo $this->get_field_name( 'posts_per_page' ); ?>" type="text" value="<?php echo ($posts_per_page) ? esc_attr( $posts_per_page ) : '5'; ?>" size="3" />
    		</p>
    		<?php
    	}
    
    	/*
    	 * сохранение настроек виджета
    	 */
    	public function update( $new_instance, $old_instance ) {
    		$instance = array();
    		$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
    		$instance['text'] =  $new_instance['text'];
    		$instance['posts_per_page'] = ( is_numeric( $new_instance['posts_per_page'] ) ) ? $new_instance['posts_per_page'] : '5'; // по умолчанию выводятся 5 постов
    		return $instance;
    	}
    }
    
    /*
     * регистрация виджета
     */
    function featured_posts_widget_load() {
    	register_widget( 'featured_posts_widget' );
    }
    add_action( 'widgets_init', 'featured_posts_widget_load' );

    В частности изменил вот в этом месте:

            $i=1;
    		$q = new WP_Query("posts_per_page=$posts_per_page");
    		if( $q->have_posts() ):
    			while( $q->have_posts() ): $q->the_post();
    
    			$alt_class = ($i++%2 ? ' tg-one-half-last' : '');
    
    			?><div class="tg-one-half<?=$alt_class?>"><?php
    Комментировать
На вопросы могут отвечать только зарегистрированные пользователи. Вход . Регистрация