• Resolved v0van

    (@v0van)


    EN:

    disadvantages of list-category-posts-0.81 plugin:

    1) I wanted to put two widgets – to display the posts of the “current” and “favorite category”.
    If “current category”=”selected category”, then the widgets are duplicated and this cannot be turned off in the plugin.
    if you select “exclude category”=1 – then the widget for category 1 does not show anything.

    2) Similarly, in the widget does not exclude the current post when displaying widgets on the post page! trifle and unpleasant.


    What I’ve done:
    + excluded the current post from the list of posts
    + disabled display on exclusion categories
    + made the title from the category names and not from the widget name
    + one common link for icon and title so that search engines index 1 link and not 2

    RU:
    Отображать 2 виджета текущая и избранная категория но без дублирования

    недостатки плагина list-category-posts-0.81:

    1) Я хотел поставить два виджета – для отображения постов “текущей” и “избранной категории”.
    Если “текущая категория”=”избранная категория”, то виджеты дублируются и это никак невозможно отключить в плагине.
    если выбрать “exclude category”=1 – то виджет для кат 1 ничего не показывает.

    2) Аналогично в виджете не исключает текущую запись при отображении виджетов на странице записи! мелочь а неприятно.


    Что я сделал:
    + исключил текущий пост из списка постов
    + запретил отображение на категориях-исключениях
    + сделал заголовок из названий категорий а не из названия виджета
    + одна общая ссылка для иконки и заголовка, чтобы поисковики индексировали 1 ссылку а не 2

    • This topic was modified 2 years, 3 months ago by v0van.
    • This topic was modified 2 years, 3 months ago by v0van.
Viewing 8 replies - 1 through 8 (of 8 total)
  • Thread Starter v0van

    (@v0van)

    include/lcp-widget.php – modified function widget()

    function widget($args, $instance) {
        global $post;
        extract( $args );
    
        $title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);
        $limit = (is_numeric($instance['limit'])) ? $instance['limit'] : 5;
        $orderby = ($instance['orderby']) ? $instance['orderby'] : 'date';
        $order = ($instance['order']) ? $instance['order'] : 'desc';
    
    	// EXCLIDE ARRAY
    	$exclude = ($instance['exclude'] != '') ? $instance['exclude'] : 0;
        
    	if($instance['excludeposts'] == 'current')
          $excludeposts = $post->ID;
        if(!isset($excludeposts))
          $excludeposts = ($instance['excludeposts'] != '') ? $instance['excludeposts'] : 0;
        $offset = (is_numeric($instance['offset'])) ? $instance['offset'] : 0;
        
    	// CAT ID
    	$category_id = $instance['categoryid'];
        
    	
    	$dateformat = ($instance['dateformat']) ? $instance['dateformat'] : get_option('date_format');
        $showdate = ($instance['show_date'] == 'on') ? 'yes' : 'no';
        $pagination = ($instance['pagination'] == 'on') ? 'yes' : 'no';
        $showmodifieddate = ($instance['show_modified_date'] == 'on') ? 'yes' : 'no';
        $showexcerpt = ($instance['show_excerpt'] == 'on') ? 'yes' : 'no';
        $excerptsize = (empty($instance['excerpt_size']) ? 55 : $instance['excerpt_size']);
        $showauthor = ($instance['show_author'] == 'on') ? 'yes' : 'no';
        $showcatlink = ($instance['show_catlink'] == 'on') ? 'yes' : 'no';
        $thumbnail = ($instance['thumbnail'] == 'on') ? 'yes' : 'no';
        $thumbnail_size = ($instance['thumbnail_size']) ? $instance['thumbnail_size'] : 'thumbnail';
        $morelink = empty($instance['morelink']) ? ' ' : $instance['morelink'];
        if ( empty( $instance['tags_as_class'] ) ) {
          $instance['tags_as_class'] = 'no';
        }
        $tags_as_class = ($instance['tags_as_class'] == 'yes') ? 'yes' : 'no';
        $template = empty($instance['template']) ? 'default' : $instance['template'];
    
    if (is_single() and $excludeposts=="") $excludeposts = $post->ID;
    // the_ID() - Displays the ID of the current post. Used inside the WordPress Loop. // the_ID() - Выводит ID текущего поста. Используется внутри Цикла WordPress.
    // If you need to get the ID, and not display it on the screen, then use the get_the_ID() function or this code: $post->ID // Если нужно получить ID, а не выводить его на экран то используйте функцию get_the_ID() или такой код: $post->ID
    
        $atts = array(
          'id' => $category_id,
          'orderby' => $orderby,
          'order' => $order,
          'numberposts' => $limit,
          'date' => $showdate,
          'date_modified' => $showmodifieddate,
          'author' => $showauthor,
          'dateformat' => $dateformat,
          'template' => 'default',
          'excerpt' => $showexcerpt,
          'excerpt_size' => $excerptsize,
          'exclude' => $exclude,
          'excludeposts' => $excludeposts,
          'offset' => $offset,
          'catlink' => $showcatlink,
          'thumbnail' => $thumbnail,
          'thumbnail_size' => $thumbnail_size,
          'morelink' => $morelink,
          'tags_as_class' => $tags_as_class,
          'template' => $template,
          'pagination_next' => '>>',
          'pagination_prev' => '<<',
          'pagination' => $pagination,
          'instance' => $this->id
        );
        $atts = array_merge(ListCategoryPosts::default_params(), $atts);
    
    	//////////////////////////////////////////
    	$cat_echo="";
    	$category_id_start = $category_id;
    	// SELECTED CATEGORY
    	// category_id=1
    	// exclude=1
    
    	// current 
    	// category_id=-1
    	// exclude=0
    
    	// if there are several digits in exclude - shows only the title of the widget // если несколько цифр в exclude - показывает только заголовок виджета 
    	// echo "<H4>category_id=$category_id<br>exclude=$exclude</H4>";
    	$exclude_arr = explode(" ", $exclude);
    	// echo "<HR>";
    	$ew=1;
    
    	//-------------------------------------------
    	if (is_archive() and $category_id_start>0 ) { // CATEG - NOT CURRENT WIDGET 
    		// echo "<p>is_archive() and category_id_start>0  SELECTED CATEG</p>";
    
    		// SO THE POSTS PANEL OF THE SELECTED CATEGORY IS NOT DISPLAYED WITHIN THE CURRENT // ЧТОБЫ ПАНЕЛЬ ПОСТОВ ИЗБРАННОЙ КАТЕГОРИИ НЕ ОТОБРАЖАЛАСЬ ПАРАЛЬЕЬНО С ТЕКУЩЕЙ 
    		if (in_array($category_id_start, $exclude_arr)) 
    		//	$ew=1;
    		//else
    			$ew="";
    
    		// $category = get_queried_object()->term_id; // DOES NOT WORK! // НЕ РАБОТАЕТ! 
    		// echo "<p>category=". implode("|", $category) ."</p>";
    		$curr_cat_id = get_queried_object()->term_id; // esc_html( $category->term_id ); 
    		// echo "<p>curr_cat_id=". $curr_cat_id ."</p>";
    		// if (in_array($curr_cat_id, $exclude_arr)) echo "<p>in_array(curr_cat_id, exclude_arr)</p>";
    		// if ($curr_cat_id==$category_id) echo "<p>curr_cat_id==category_id</p>";
    		if (in_array($curr_cat_id, $exclude_arr) or ($curr_cat_id==$category_id) ) $ew="";
    		// $cat_echo = '<a href="'. get_category_link( $category->term_id ) .'" rel="category tag" class="a_current_category">' . esc_html( $category->name ) .'</a>';
    
    		$cat_echo = '<a href="'. get_category_link( $category_id_start ) .'" rel="category tag" class="a_current_category">' . get_cat_name( $category_id_start ) .'</a>';
    
    	}
    	//-------------------------------------------
    
    	elseif (is_single()) { // POST - CURRENT WIDGET 
    		// echo "<p>is_single()</p>";
    
    		if ($category_id_start<0) { // CURRENT WIDGET 
    			// echo "<H4>CURRENT</H4>";
    			// $cat = get_the_category($post->ID);
    			// $cat->term_id // ID категории
    			// $cat->name  // Название категории
    			// $cat->slug // Ярлык категории
    		
    			$categories =  get_the_category($post->ID);
    			$cat_names=array(); 
    			$cat_ids=array(); 
    			//$ew=1;
    			foreach ( $categories as $category ) {
    				$curr_cat_id = esc_html( $category->term_id ); 
    				//$cat_ids[] = esc_html( $category->term_id ); 
    				if (in_array($curr_cat_id, $exclude_arr)) $ew=""; // категория в списке запрещённых 
    				$cat_ids[] = $curr_cat_id;
    				// $cat_names[] = esc_html( $category->name );
    				$cat_names[] = '<a href="'. get_category_link( $category->term_id ) .'" rel="category tag" class="a_current_category">' . esc_html( $category->name ) .'</a>';
    			}
    			// $cat_ids - ALL category ids // $cat_ids - ВСЕ id категорий 
    			$cat_echo = implode("<br>", $cat_names);
    			// $cat_echo = implode("<br>", $cat_names);
    			// echo "<p>cat_ids=". implode("|", $cat_ids) ."</p>";
    
    		} else {  // SELECTED CATEG
    			// echo "<p>SELECTED CATEG</p>";
    			//$ew=1;
    			if (in_array($category_id_start, $exclude_arr)) 
    				$ew="";
    			$cat_echo = '<a href="'. get_category_link( $category_id_start ) .'" rel="category tag" class="a_current_category">' . get_cat_name( $category_id_start ) .'</a>';
    		}
    
    	}
    	//-------------------------------------------
    	else {
    			// echo "<p>!is_single() and !(is_archive() and $category_id_start>0 )</p>";
    			//$ew=1;
    			if (in_array($category_id_start, $exclude_arr)) 
    				$ew="";
    			$cat_echo = '<a href="'. get_category_link( $category_id_start ) .'" rel="category tag" class="a_current_category">' . get_cat_name( $category_id_start ) .'</a>';
    	}
    	//-------------------------------------------
    
    // https://wp-kama.ru/function/get_the_category
    // Вывод ссылок на рубрики поста
    /*
    foreach ( get_the_category() as $category ) {
    	printf(
    		'<a href="%s" class="link link_text">%s</a>', // Link output template // Шаблон вывода ссылки
    		esc_url( get_category_link( $category ) ), // Link to rubric // Ссылка на рубрику
    		esc_html( $category->name ) // Category name // Название рубрики
    	);
    }
    */
    
    // echo "<H4>ew=$ew</H4>";
    
    if($ew==1) {
    
        echo $before_widget;
    	// echo " <Hr> "; 
    
        if ($pagination === 'yes') lcp_pagination_css();
    
        // To make the widget title replacement work with "Current category" we need to
        // run the displayer here to determine the current cat id.
        // Otherwise the id remains set to "-1".
        $catlist_displayer = new CatListDisplayer($atts);
        $lcp_display = $catlist_displayer->display();
    
        // Fetch the category id from the Catlist instance.
        $category_id = $catlist_displayer->catlist->get_category_id();
        if ((is_null($category_id) || [0] === $category_id ) &&
            ($title == 'catlink' || $title == 'catname')) {
          $title = '';
    	  // echo "<p>is_null($category_id</p>";
        } elseif ($title == 'catlink') {
          // If the user has setup 'catlink' as the title, replace it with
          // the category link:
          $lcp_category = get_category($category_id);
          $title = '<a href="' . get_category_link($lcp_category->cat_ID) . '">' .
            $lcp_category->name . '</a>';
    	  // echo "<p>title == 'catlink'</p>";
        } elseif ($title == 'catname') {
          // If the user has setup 'catname' as the title, replace it with
          // the category link:
          $lcp_category = get_category($category_id);
          // $title = $lcp_category->name;
          $title = '<a href="' . get_category_link($lcp_category->cat_ID) . '">' .
            $lcp_category->name . '</a>';
    	  // echo "<p>title == 'catname'</p>";
        } else {
    	//====================
    		//if ($cat_echo<>"") {
    		// if ($category_id_start<0) {
    			$title = $cat_echo;
    			// echo "<H4>category_id_start<0</H4>";
    		//}
    	//====================
    	}
    
        echo $before_title . $title . $after_title;
    	// echo "<H4>================</H4>";
        echo $lcp_display;
        echo $after_widget;
    }
    Thread Starter v0van

    (@v0van)

    include/lcp-catlistdisplayer.php – modified

      private function build_output($tag){
    . . . 
    //Give a class to wrapper tag
        if (isset($this->params['class']))
          $this->lcp_output .= ' class="' . $this->params['class'] . '"';
    	else { 
    		if ($tag == 'ul')
    			$this->lcp_output .= ' class="lcp_ul"';
    		if ($tag=='ol' )		
    			$this->lcp_output .= ' class="lcp_ol"';
    		if ($tag=='li' )	
    			$this->lcp_output .= ' class="lcp_li"';
    		if ($tag=='p' )	
    			$this->lcp_output .= ' class="lcp_p"';
    	}
    . . .
    // private function get_post_link($single, $text, $class = null){
      private function get_post_link($single, $text, $class ="lcp_postlink"){
    	// $info = '<span class="span_lcp_thumbnail">'. $this->get_thumbnail($single) . '</span>';
    	// $info = '<a href="' . get_permalink($single->ID) . '" title="' . wptexturize($single->post_title) . '"';
        $info .= '<div class="lcp_div_postlink"><a class="lcp_postlink" href="' . get_permalink($single->ID) . '"';
        if ( !empty($this->params['link_target']) ):
          $info .= ' target="' . $this->params['link_target'] . '"';
        endif;
    
       // if ( !empty($class ) ):
       //   $info .= ' class="' . $class . '"';
       // endif;
    
        $info .= '><span class="span_lcp_thumbnail">'. $this->get_thumbnail($single) . '</span> <span class="span_lcp_anchor">' . $text . '</span></a><div>';
        if($single->post_status == 'private'):
            $info .= '<span class="lcp_private"> private</span>';
        endif;
    
        return $info;
      }
    • This reply was modified 2 years, 3 months ago by v0van.
    • This reply was modified 2 years, 3 months ago by v0van.
    Thread Starter v0van

    (@v0van)

    include/lcp-thumbnail.php – make $lcp_thumbnail without link

    //$lcp_thumbnail = '<a href="' . esc_url(get_permalink($single->ID)) . '" title="' . esc_attr($single->post_title) . '">';
    
            $lcp_thumbnail .= get_the_post_thumbnail(
                $single->ID,
                $lcp_thumb_size,
                array(
                    'alt' => esc_attr($single->post_title),
                    // If we have a class use it, otherwise use default
                    'class' => ( $lcp_thumb_class != null ) ? $lcp_thumb_class : 'lcp_thumbnail'
                )
            );
            // $lcp_thumbnail .= '</a>';
    Thread Starter v0van

    (@v0van)

    this my final modified plugin arhive https://disk.yandex.ru/d/5CLDJFqaw5mK5g

    Thread Starter v0van

    (@v0van)

    EN:
    it turns out that now I can not update the plugin, because I made too many changes to it. at the moment everything is working.
    accordingly, I ask you to make my changes to the plugin so that other users can use them and so that I can update in the future.
    I don’t plan to make my own plugin out of yours.

    RU:
    получается что теперь я не могу обновлять плагин, так как внёс в него слишком много изменений. в данный момент всё работает.
    соответственно прошу вас внести мои изменения в плагин, чтобы ими пользовыались другие пользователи и чтобы я мог обновлять в будущем.
    я не планирую делать свой отдельный плагин из вашего.

    Plugin Contributor zymeth25

    (@zymeth25)

    Hi, as per the How to get help post and the plugin’s description + documentation, code changes should be discussed on Github and submitted as pull requests. So please head there if you would like your changes to be included.

    Thanks

    • This reply was modified 2 years, 3 months ago by zymeth25.
    Thread Starter v0van

    (@v0van)

    EN:
    I never use GitHub. religion forbids.
    Extremely inconvenient and non-working interface.
    GitHub is clinical russophobes just like facebook.
    GitHub began blocking accounts of russian companies and developers
    Don’t recommend this crap to anyone!!

    RU:
    Я никогда не пользуюсь GitHub. религия запрещает.
    Крайне неудобный и неработающий интерфейс.
    GitHub – это клинические русофобы также как facebook.
    GitHub начал блокировать аккаунты российских компаний и разработчиков
    никому не советуйте эту гадость!!

    • This reply was modified 2 years, 3 months ago by v0van.
    • This reply was modified 2 years, 3 months ago by v0van.
    Plugin Contributor zymeth25

    (@zymeth25)

    GitHub suspends accounts of people and companies under sanctions introduced because of the Russian invasion of Ukraine, this is true. They do not ban other Russian developers, though. If you have a problem with that you are free to stop using GitHub but we are very unlikely to find the time to create the pull request ourselves. In short – if you do not use Github your changes might not be merged into the plug-in.

    • This reply was modified 2 years, 3 months ago by zymeth25.
Viewing 8 replies - 1 through 8 (of 8 total)
  • The topic ‘Display 2 widgets current and favorite category but no duplication’ is closed to new replies.