Is category wordpress


Do you need to display posts from a specific category on a custom page template? Doing so, you can use your own template design for post listing on a WordPress page. In this article, we study how to display posts from a specific category on a custom page template.

By default in WordPress, you can categorize your post. This feature is useful to find out in which category your posts belongs to. In WordPress, when a user clicks on one of the categories they will redirect to post listing page for that specific category. WordPress uses the following template files for posts listing of a category.

  • category-slug.php
  • category-ID.php
  • category.php
  • archive.php
  • index.php

To display posts, WordPress search for template files in the above order. Whichever template file found first, that files code would use for category’s posts listing.

It’s all about default WordPress templates. But, what if someone wants to use a custom page template for posts listings from a specific category?

Let’s go through step by step guide to achieve our goal.

Create Page Template In WordPress

Our goal is to display posts by the category on a page. Obviously, we need to write a code for it.

Create a file template-category.php


in your themes directory and add the below comment at the top of file.

template-category.php

<?php  /**   * Template Name: Category Custom Page   */    ?>  

Next, go to your WordPress dashboard, create your page where you want to display posts. Assign our template to this page.

Is category wordpress

Display Posts From Specific Category

We have assigned our template to the WordPress page. Next thing needs to do is write a code which fetches posts attached to a category.

We will use WP_Query class to fetch the posts. For instance, we assume you have a category called ‘WordPress’ which posts you need to display.

$args = array(  	'post_type' => 'post',  	'post_status' => 'publish',  	'category_name' => 'wordpress',  	'posts_per_page' => 5,  );  $arr_posts = new WP_Query( $args );    if ( $arr_posts->have_posts() ) :    	while ( $arr_posts->have_posts() ) :  		$arr_post.  

t;">Read More</a> </div> </article> <?php endwhile; endif;

In the above code we have passed 'category_name' => 'wordpress'. Here ‘wordpress’ is the slug of a category.

Is category wordpress

We can also pass category id instead of category_name.

$args = array(  	'post_type' => 'post',  	'post_status' => 'publish',  	'cat' => '4', //we can pass comma-separated ids here  	'posts_per_page' => 5,  );  

posts_per_page is the number of posts to fetch from the database. We have used have_posts() method which checks whether posts are available for WordPress loop. If posts are available then we loop through each post and display it.

Pagination

The code we have written only fetches limited posts from the category. But, what if we have assigned more posts to the category. In that case, we need a paginate links.

For pagination you need to install and activate the plugin WP-PageNavi.

This plugin provides a method wp_pagenavi()


which generates a paginate links on the posts listing page.

Is category wordpress

To add paginate links in our WordPress page, we need to modify our code. First, we need to pass paged parameter and then use the function wp_pagenavi().

We will get the value for paged as follows:

$paged = (get_query_var( 'paged' )) ? get_query_var( 'paged' ) : 1;  

So below is our final code.

template-category.php

<?php  /**   * Template Name: Category Custom Page   */    get_header(); ?>    <div id="primary" class="content-area">  		<main id="main" class="site-main" role="main">    		<?php  		$paged = (get_query_var( 'paged' )) ? get_query_var( 'paged' ) : 1;  		$args = array(  			'post_type' => 'post',  			'post_status' => 'publish',  			'category_name' => 'wordpress',  			'posts_per_page' => 5,  			'paged' => $paged,  		);  		$arr_posts = new WP_Query( $args );    		if ( $arr_posts->have_posts() ) :    			while ( $arr_posts->have_posts() ) .  

lt;a href="<?php the_permalink(); ?>">Read More</a> </div> </article> <?php endwhile; wp_pagenavi( array( 'query' => $arr_posts, ) ); endif; ?> </main><!-- .site-main --> </div><!-- .content-area --> <?php get_footer(); ?>

Of course, you can change the HTML tags to fit with your website design.

We hope you understand how to display posts from the specific category on a WordPress page. Please share your thoughts in the comment section below.

Related Articles

  • How to Load WordPress Post With AJAX
  • How To Set Featured Image Programmatically In WordPress
  • How To Set Correct File Permissions For WordPress

If you liked this article, then please subscribe to our Youtube Channel for video tutorials.

artisansweb.net

1. Главная страница

Часто хотим, чтобы определенная информация выводилась только на главной странице. Для решения можно создать в папке Вашей темы файл home.php


или в файл index.php внести следующее условие:

  <?php if(is_home()) { ?>  <div>  ....Здесь выводим информацию,  которую мы хотим видеть на главной странице  </div>  <?php } ?>

2. Проверяем рубрики

Зададим такое условие: Если мы находимся в рубрике WordPress, то выведем фразу «Вас приветствует, WordPress!», а если нет то фразу «Добро пожаловать, на наш сайт!»

  <?php if(is_category('id')) :  echo "Вас приветствует, WordPress!";  else :  echo "Добро пожаловать, на наш сайт!";  endif;  ?>    /*Можно и такой схемой*/  <?php if(is_category('id')) { ?>  <p>"Вас приветствует, WordPress!"</p>  <?php } else { ?>  <p>Добро пожаловать, на наш сайт!"</p>  <?php } ?>

Здесь и дальше в качестве идентификатора рубрики(метки) или записи(страницы) я буду использовать id — его можно узнать в панели управления сайтом. Если Вы пишете условия для рубрик(меток) то смотрите id на странице рубрик(меток), а если записей(страниц) — то на странице всех записей(страниц)… паника). Как все-таки узнать?, — смотрите иллюстрацию:


Полноценно используем условие if

Идем далее по условиям связанных с рубриками и зададим следующее: «Если запись находится в рубрике WordPress, то вывести слова — Статья из рубрики WordPress»:

  <?php if(in_category('id')) :  echo 'Статья из рубрики WordPress';  endif; ?>

И еще такой финт ? допустим нам нужно условие для проверки нескольких рубрик, тогда условия будут иметь вид:

  <?php if(is_category(array(1,2,34,48)) or in_category(array(1,2,33,50))) : ?>  <p>выведем то, что нам нужно</p>  <?php endif; ?>

3. Проверяем метки

Метки — крутой классификатор внутри рубрик. Рассмотри несколько примеров, как их можно проверить.

Задача: Если запись имеет метку "plugin", то вывести фразу — WordPress Plugin

Решение:

  <?php if(has_tag('plugin')) :  echo 'WordPress Plugin';  endif; ?>

Задача: Если находимся на странице метки "plugin", то вывести фразу — Коллекция плагинов WordPress.

Решение:

  <?php if(is_tag('plugin')) :  echo 'WordPress Plugin';  endif; ?>

Примечание: в работе с условиями меток лучше пользоваться ярлыком метки, а не ее идентификатором.

Заключение


Я рассмотрел основные условные теги, если у Вас есть какие-то вопросы задавайте их в комментариях! Удачного использования!

www.howtomake.com.ua

Работающие примеры

Здесь несколько примеров для демонстрации того, как следует использовать условные теги.

Одиночный пост

Этот пример показывает как использовать условный тег is_single () для того, чтобы отобразить информацию только на странице одиночного поста:

<?php if (is_single())
{
echo 'Это один из постов в рубрике ' . single_cat_title() . ', вот так!';
}
?>

Разница, основанная на дате

Если кто-то просматривает ваш блог по датам, то он увидит «помеченные» посты разных лет разным цветом бэкграунда:

<?php
// начинаем Цикл
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2 id="post-<?php the_ID(); ?>">
<a href="<?php the_permalink() ?>" rel="bookmark" title="Постоянная ссылка <?php the_title(); ?>">
<?php the_title(); ?></a></h2>
<s.

';
}
} else {
echo '<div class="entry">';
}
the_content('Далее »');
?>
</div>

Разный контент в боковой колонке (сайдбаре)

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

<!-- начало боковой колонки -->
<div id="sidebar">
<?php
// let's generate info appropriate to the page being displayed
if (is_home()) {
// на главной странице покажем список рубрик первого уровня:
echo "<ul>";
wp_list_cats('optionall=0&sort_column=name&list=1&children=0');
echo "</ul>";
} elseif (is_category()) {
// на странице рубрики покажем все рубрики всех уровней
echo "<ul>";
wp_list_cats('optionall=1&sort_column=name&list=1&children=1&hierarchical=1');
echo "</ul>";
} elseif (is_single()) {
// на странице одиночного поста покажем... что-нибудь, впишите сами:


} elseif (is_page()) {
// на странице Постоянной страницы. А какой именно?
if (is_page('Обо мне')) {
// Постоянная страница About
echo "<p>Это страница обо мне!</p>";
} elseif (is_page('Используемые плагины')) {
echo "<p>На этой странице список используемых плагинов, я использую WordPress версии " . bloginfo('version') . "</p>";
} else {
// для всех других Статичных страниц
echo "<p>Привет, я Педро!</p>";
}
} else {
// для всех остальных типов страниц (архивов, страницы рез-тов поиска, 404 ошибки и т.д.)
echo "<p>Педро славный парень.</p>";
} // на этом все!
?>
<form id="searchform" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div>
<input type="text" name="s" id="s" size="15" />
<input type="submit" value="<?php _e('Search'); ?>" />
</div>
</form></div>
<!-- конец боковой колонки -->

www.wp-info.ru

Ever wanted to exclude a category in WordPress? Turns out it’s pretty easy to do without having to install another plugin.

Exclude category in WordPress

This is probably the fastest way to exclude category in WordPress besides using a plugin.

To exclude category from main page change is_feed to is_home. Or if you want to exlude for both feed and main page, change if ($query->is_feed) {


to if ($query->is_feed || $query->is_home) {

Add the following to your theme’s functions.php file:

function exclude_category($query) { 	$query->set('cat','-1'); 	return $query; } add_filter('pre_get_posts','exclude_category');

If you want to exclude multiple categories, replace the second line with this:

$query->set('cat','-1,-2,-3');

Conditional category exclusion

What if you only want to exclude the category from something specific, like say your feeds? Easy, just a little modification to the previous technique:

function exclude_category($query) { 	if ($query->is_feed) { 		$query->set('cat','-1'); 	} 	return $query; } add_filter('pre_get_posts','exclude_category');

Here’s an example of excluding a category only on the home page:

function exclude_category($query) { 	if (is_home()) { 		$query->set('cat','-1'); 	} 	return $query; } add_filter('pre_get_posts','exclude_category');

Alternate method

Here is another way to exclude a category from within the WordPress loop:

<?php if (in_category('1')) continue; ?>

This instructs WordPress to skip any posts in category “1”. Here is another way of writing the condition:

<?php if (!in_category('1')) {  	// do something for categories that aren't ID = 1 } else { 	// skip any posts from category with ID = 1 	continue; } ?>

Another alternate method

Lastly, you can instruct the WordPress loop to exclude specific categories:

<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts($query_string . '&cat=-1&paged=$paged'); ?>

In addition to query_posts(), you can use WP_Query with similar syntax.

wp-mix.com

Remove Category from WordPress URLs

Below different ways to achieve the same. Just note that if you have a fresh WordPress installation then setup permalinks as you wish. But if you change permalinks structure on a live site, properly redirect old URLs to new ones to avoid loses.

Remove Category from WordPress URLs with a Dot

1. Go to Settings -> Permalinks.
2. Select Custom Structure and put /{136ce94cc7fec1f5657bab0b4d73ed308318c1024f899c463e79e42d4b375fbf}category{136ce94cc7fec1f5657bab0b4d73ed308318c1024f899c463e79e42d4b375fbf}/{136ce94cc7fec1f5657bab0b4d73ed308318c1024f899c463e79e42d4b375fbf}postname{136ce94cc7fec1f5657bab0b4d73ed308318c1024f899c463e79e42d4b375fbf}/ there.
3. Assign a dot to Category base field and save the change.

Remove category slug using dot

Note that providing dot to Category base in settings is the must. As leaving it blank will use the default value. Visit a post after saving settings and check the URL, it won’t have the category base now. While this trick currently works, there’s no assurance that it will work in the future as well.

Remove Category From Your URLs with .htaccess

RewriteRule ^category/(.+)$ http://www.yourwebsite.com/$1 [R=301,L]

You can also add this code to your .htaccess file through FTP rather than using a dot. Add the code before the closing </IfModule> tag in the file and it will remove the category slug from WordPress permalink.

Are You using Yoast SEO Plugin?

The current version of SEO by Yoast plugin has discontinued the option of category removal from URLs. Past version had the option in the Advanced menu of plugin settings. The websites who’re using Yoast for a long time, still have their URLs without the category base.

If you’ve installed Yoast plugin on your fresh WordPress website, check the post URLs as well. While we’re not sure, the feature might be still there and working silently. Else there are other plugins as well to remove category slug.

If you’re about to launch a WordPress website then don’t forget reading 10 checks before you launch it.

Removing Category from Slug using a Plugin.

The plugin Remove Category URL seems quite popular and offers additional advantages. You can try the plugin if your website is older than 6 months. It will redirect the old category permalinks to the new ones, which is better for SEO. Also, you don’t need to configure anything or modify a file. Get the WordPress official plugin URL here.

FV Top Level Categories is one another plugin to remove category base from WordPress Permalinks.

Writing a function is also a way for the functionality but it makes the site slower. At last, all four ways to remove the category slug from URLs are there. Which one do you prefer or any feedback/question? Let us know it the comment section below and try resolving.

themerella.com

Tutorial to exclude category from WordPress blog page

  1. Login to your WordPress dashboard and find the WordPress category ID of the category you would like to exclude. Read How to Find a WordPress Category ID to learn how to find out the category ID.
  2. Once logged in, also list down the name of WordPress theme you are using by navigating to the Appearance > Themes node.
  3. Connect to your WordPress using FTP and navigate to the theme’s directory. If the theme name is ‘default’, the directory of the theme is /wp-content/themes/default/.

WP White Security WordPress tip: You can modify a theme file from the built-in WordPress Editor (Appearance > Editor). Though it is always recommended to do theme and other WordPress files updates offline (via FTP like explained in this WordPress tutorial) so you can test the change and easily revert back if something goes wrong, such as a WordPress whitescreen.

  1. Download the theme’s file functions.php (e.g. /wp-content/themes/default/functions.php). Before doing any changes to the file, make a backup of such file in case you need to quickly revert back the changes.
  2. Copy the below code and paste it in functions.php file, right before the ?> (at the bottom of the file). If you want to add a comment to recognize the code at a later stage, you can do so by using the ‘//’ signs at the beginning of the comment line.

PHP code to exclude WordPress category from blog

 function exclude_category($query) { if ( $query->is_home() ) { $query->set('cat', '-xx'); } return $query; } add_filter('pre_get_posts', 'exclude_category'); 
  1. Replace the xx (mentioned in line 3 of the above code) with the category ID you recorded in step 1 of this WordPress tutorial. Leave the minus ‘-‘ sign in front of the category ID, only replace the xx.
  2. Once ready, save the file and upload it back to your website. Refresh the page and you should notice that the excluded categories are not showing up in the WordPress blog.

Excluding multiple WordPress categories from blog

To exclude multiple categories from showing up in the WordPress blog page, simply add all of the categories ID in the same line from the code above (line 3) separated by a space as per the example below.

 $query->set(‘cat’, ‘-124 -125 -126’); 

The example code above would exclude the categories with ID 124, 125 and 126.

www.wpwhitesecurity.com

Query Posts

Query Posts используется для контроля над выводом постов внутри цикла. С его помощью можно управлять тем, что выводить, когда выводить и как выводить.

8) Выводим последние посты

последние 5 постов:

9) Посты определённой категории

Выводим 5 постов категории с categoryID 2

10) Исключить категорию

Допустим, нам нужно исключить отображение какой- либо категории (categoryID 2):

Произвольные поля (Custom Field )

Custom Field — очень полезная вещь, довольно часто используется для вывода информации после поста. Используется, например, для вывода информации об авторе поста.

11) Как добавить картинку с ссылкой на сам пост

Для начала добавим Произвольное поле в пост.

Is category wordpress

Чтобы отобразить изображение и прикрепить к нему ссылку на пост, помещаем следующий код в цикл (перед самим текстом поста):

Не забывайте, что произвольных полей после поста может быть несколько. Похожий эффект можно увидеть на Best Web Gallery, где подобным образом отображены миниатюры, ссылки URL и подсветка информации. Также о произвольных полях можно почитать в данной статье — использование custom fields в WordPress.

WP List Pages

Тег wp_list_pages используется для отображения списка страниц в хедере и сайдбаре

12)Site map

Для того, чтобы отобразить Site map, достаточно добавить этот код в страницу sitemap.php

Замечу, что pageID 12 исключена, т.к. это страница — сама sitemap.php, и её не нужно отображать…
Метод работает, хотя, наверное, лучше воспользоваться более стандартным методом и построить карту сайта с помощью плагина dagon design sitemap generator.

13) Динамичное субстраничное меню

Добавьте этот код в sidebar.php и он отобразит субстраничное меню, если субстраницы есть на этой странице:

14) Тема страницы

Хорошо бы не упускать и такую функцию как Page Template, которая позволяет задавать новую тему для вашего блога. Для начала, нужно создать саму тему, затем нужно обозначить странице своб собственную тему. Вот как она выглядит (напр., portfolio.php)

При написании или редактировании страницы, справа можно будет увидеть “Page Template”, и там указать нужную тему.

Is category wordpress

wordpressinside.ru


You May Also Like

About the Author: admind

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.