Display blog posts on any page (with navigation). Displaying custom WordPress post types Wordpress how to display posts on a specific page

Have you ever tried to change the default order of posts on a blog page? By default, posts are ordered based on publication date, and there is no easy way to change the order they appear.

If you want to change the order in which posts are displayed, you have three options: change the post's publication date, write some code to sort the post using parameters other than the publication date, or find a plugin that does the work for you.

Changing the publication date is not the best approach for most blogs. Thus, in this article we will consider the second and third options. First, I'll show you how to write a plugin to customize the order of your posts. Next, we'll look at two plugins from the WordPress repository that we'll use to create a custom post order.

We write our own plugin to display posts

There are two main steps required to implement your own post order:

  1. Add a custom field that will be used as a basis for sorting posts.
  2. Implement a custom sort order by modifying the main WordPress loop or creating a custom loop and adding it to a custom page template or sidebar widget.

Let's start by adding a custom field, which is done in the WordPress post edit screen. However, before you do this, you will need to enable your development environment, create a plugin folder, and then create a plugin file in that folder. If you want to know what the plugin structure looks like, you can see the finished product on GitHub.

Create a custom field

You can use custom fields in the post edit screen to add metadata to each post, however I prefer to add a custom meta panel with the field to the backend. This will help you avoid accidentally entering metadata into the wrong field.

The first step to adding a custom meta panel to the backend is to create the panel and link it to the post edit screen:

This piece of code, included in your plugin file, will allow you to create a custom meta panel. This is what the panel will look like:

You may notice the 'jpen_custom_post_order' callback function in the code. Let's create this function next and add it to our plugin file. This will add the field to the meta panel we created above.

ID, "_custom_post_order", true); ?>

Enter the position at which you would like the post to appear. For exampe, post "1" will appear first, post "2" second, and so forth.

The code snippet begins with a task. We then create a variable $current_pos and assign it the value of the current sort order of the records. Next are two p elements that create the visible content of the meta panel. The current value, if it exists, is then printed in the field.

Here we first check that the nonce is set and then we check for user permissions to make changes to the record. If the check is successful, the post metadata is updated with a new value for the random order in which the posts are displayed.

Display a custom field in the admin panel

In the last section, we added a custom meta panel to the post editing screen - it will store a numeric value. A little later we will use this numerical value to create our own order for displaying records. However, we need to solve one more problem before that.

To see the post sort order value for the current post, we must open that post and look at the custom meta panel we added to the post edit screen. This is not very convenient. Let's add a sort order value to the post output page in the admin panel so we can quickly see the value associated with each post.

First, we need to add a custom column to the list of entries in the admin area. We will do this with the following code:

"Position",)); ) add_filter("manage_posts_columns" , "jpen_add_custom_post_order_column"); ?>

Then we need to get the record order value for each record and output that value in a new column. It's not that difficult and we'll do it with the following function:

" . get_post_meta($post_id, "_custom_post_order", true) . "

"; ) ) add_action("manage_posts_custom_column" , "jpen_custom_post_order_value" , ​​10 , 2); ?>

Wonderful. Now, if we visit the list of blog posts in the admin panel, we can easily see which posts have been assigned the new display order.

This is what it will look like in the admin panel:

Ways to use custom post order

Now that we've implemented the ability to assign a custom output order to records, it's time to put this option to good use. We need to answer the question: “How exactly do we want to use random ordering of records?”

There are several different options for how you can apply custom sorting. Here are a couple of ideas:

  • Sort all posts in random order and display the sorted list on the blog posts page. You probably won't want to do this on a blog that's actively populated, but if you're using WordPress to publish a series of tutorials that aren't updated as often, you might want to resort to sorting posts in random order.
  • Create a curated list of posts and display these posts in any convenient order using custom page templates. For example, you can create a list that contains only posts from a certain category, and sort these posts in any convenient order.
  • Create a list of blog posts that will start with a few randomly sorted entries, after which the remaining posts will be included in the usual order.

There are no limits. If you find a use for random ordering of entries and know how to implement it, great! Let's look at all three ideas outlined above to understand how they would work in practice.

Changing posts on a blog page to a randomly sorted list

The easiest way to use a random order for displaying posts is to replace the standard list of posts on a blog page with a randomly sorted list. To do this you must put the following function in your plugin:

is_main_query() && is_home())( $query->set("orderby", "meta_value"); $query->set("meta_key", "_custom_post_order"); $query->set("order" , " ASC"); ) ) add_action("pre_get_posts" , "jpen_custom_post_order_sort"); ?>

Keep in mind that this function will only include records that have been associated with a custom output order value. All other posts without such a link will not be displayed on the blog page. In other words, if you do this, you will need to bind a custom output order value to all records that need to be output to the screen.

Creating a curated list of randomly sorted records

Creating a curated list of randomly sorted posts requires the use of the WP_Query class. You will need to create a query that includes the parameter you want to use to list the entry, and then you will need to add a custom sort order to the query. This is what the code will look like:

"post", "cat" => "94", "meta_key" => "_custom_post_order", "orderby" => "meta_value", "order" => "ASC"); $query = new WP_query ($args); if ($query->have_posts()) ( while ($query->have_posts()) ( $query->the_post(); /* only list posts that have a current custom post order value */ if (!empty( get_post_meta($post->ID, "_custom_post_order", true))) : ?> /* insert code for rendering posts */

This query will first select all records that belong to the category with ID = 94. Next, it will select records that have a random output order value. Finally, it will sort these records in the desired order.

This request can be placed in a custom page template or added to a sidebar widget to display the requested records.

Add sorted posts to the beginning of the list of blog posts

Another option for implementing sorting is to add randomly sorted posts to the beginning of the list of blog posts, after which the rest of the blog posts will go, sorted in the usual order. This will be more difficult to do - we will need to create two custom queries using the WP_Query class.

The first query will receive randomly sorted records and display them according to the sort value. However, we only need the list of randomly sorted posts to be presented on the first page of the blog, so we will need to also add an if condition that will check if the page is the first one.

The second query will get all the records and sort them in the usual order. However, it will skip all those records that have a custom sort value assigned to them. To enable pagination for the posts returned in the second query, we will need to work with the $wp_query global variable.

Here's one way we could combine two queries to get the desired result:

"post", "meta_key" => "_custom_post_order", "orderby" => "meta_value", "order" => "ASC"); $query1 = new WP_query($args1); if ($query1->have_posts()) : while ($query1->have_posts()) : $query1->the_post(); // This if statement will skip posts that were assigned a custom sort value and then had that value removed if (!empty(get_post_meta($post->ID, "_custom_post_order", true))) : // Display the custom sorted posts ?>

"); ?> ">Read More

"post", "orderby" => "date", "order" => "DESC", "paged" => $paged); // For pagination to work, must make temporary use of global $wp_query variable $temp = $wp_query; $wp_query = null; $wp_query = new WP_query ($args2); if ($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post(); // Skip posts with custom sort value if (!empty(get_post_meta($post->ID, "_custom_post_order", true))) ( continue; ) // Display the standard sorted posts ?>
", esc_url(get_permalink())), ""); ?> ">Read More

You can use this set of queries to replace the standard query for a blog page. This is done in three steps:

  1. Create a home.php file by copying the Index.php of the parent theme.
  2. We place these queries instead of the base loop.
  3. Upload the new home.php to the root directory of the child theme.

Now, when the blog page is rendered, the new home.php file will be used as the page template.

Plugins to achieve the same goals

If you're not a developer or don't need the flexibility of custom solutions, you can take advantage of several plugins that are available in the WordPress.org plugin directory. With their help, you can make sorting records easier. However, many of the available solutions are poorly supported or not regularly updated. Let's look at two options that are actively supported by their developers and have regular updates.

Post Types Order

Post Types Order is active on more than 400,000 sites and is constantly updated; The developer actively resolves issues received by support. The plugin has a rating of 4.6 out of 5 and has collected more than 150 reviews from users.

The plugin can be used to custom sort posts and post types. To use the plugin, simply install and activate it, then go to Settings > Post Types Order. Next, visit the list of records in the admin panel and simply drag and drop the records into the desired section with the sort order. As a result, you will see that the posts on the front end of your site have been sorted in the order you need.

Order Your Posts Manually

Order Your Posts Manually is active on less than 1000 WordPress sites. However, it has a good rating of 4.6 out of 5 and the developers resolve all support requests. The plugin is really worth considering.

To use the plugin, install it, activate it and go to Settings > Order Your Posts Manually. Configure a few options and click Order My Posts. Clicking this button will take you to Tools > Order Your Post Manually and generate a list of all your posts. Simply drag your entries into the desired group to organize them, then click Save Changes.

We have a separate template file for displaying posts on WordPress – single.php. However, this is the output of a single record within a loop, which is determined by the functions of the free engine and does not create any complexity. But how to display wordpress posts on another page or on the main page?


get_posts()

In this case, we need the get_posts() function. With its help, we can access all posts according to the criteria we need. This method has quite a lot of advantages, one of them is the ability to sort posts by date, title, ID, etc. The list of all arguments is quite large, you can view it in the WordPress code, but we will look at a direct example of only the most necessary set for execution assigned task.

So, the principle of the function:

$posts = get_posts($args);

As you understand, in the $args variable we set all the necessary parameters for displaying our posts. In the posts variable we receive an array of data that is ready to be output in a loop. After completing the loop, don’t forget to use the wp_reset_postdata() function, which will allow us to avoid bugs on the page with additional loops associated with displaying posts. Our code will look like this:

9 , "category" => 1, "orderby" => "date"); $myposts = get_posts($args); foreach($myposts as $post)( setup_postdata($post); ?>

">

This is a completely ready-made code for inserting into the desired place in your theme template. Let me explain a little about the given arguments. In the numberposts parameter we set the number of posts to be displayed, in category we indicate the category ID, and orderby is responsible for sorting by date.

The loop already uses a regular template that displays a thumbnail, post link, title, and publication date. As you can see, everything is quite simple, now you can display WordPress posts anywhere in your theme.

Using WordPress, as a regular blog engine with a ready-made theme, such a question would not arise for us. We simply do not interfere with work algorithms CMS, the records themselves are somehow displayed. In which case output WordPress posts is it starting to interest us?

Then when we gather from the static HTML make the layout unique WordPress topic. More precisely, we want to offer our services for stretching layouts on WordPress. So, without skill display WordPress posts anywhere on the site - you will not be able to get by.

WordPress Theme Structure

What is the theme WordPress? This is a set of files (templates) consisting of HTML code mixed with PHP code. Any theme should have at least two files: index.php And CSS styles file. HTML the code is the layout of the unique design, and PHP the code consists of functions and tags already described in the kernel WordPress, we never touch kernel files.

Remember that all HTML the code must be outside the opening and closing tags PHP. On the contrary, all PHP The code is written only inside tags. For example, we will display the name of the author of the post in WordPress loop:

In the code WordPress It describes in detail what these template tags do and how to display them on the site. To create a topic WordPress from scratch, you need to know a set of these template tags and how to apply them.

WordPress Post Template Tags

the_permalink
the_title
the_time
the_content
the_author
the_excerpt
the_category

These template tags are used to display articles on the home page WordPress in the template index.php.

">

We display the date the record was created:

Let's display the article itself - the content, inside the tag div:



Attention! Nothing came out. Why? Because these template tags only output inside a loop, they don't work outside of a loop. We must place all this code inside a loop. All PHP And HTML The code inside the loop will be repeated as many times as we have records. See the code below.



We put all the code above here. We are inside a cycle.



Let's understand what the code above means. We set the condition that if there are records in the database, the title, creation date and content of the record will be displayed.

If there are posts, then in a cycle while function is running the_post who deals displaying all records, as long as they exist.

Finished the loop and condition.


The cycle will run as long as there are records, the number output of records per page is set in the blog settings. If there are more entries, then pagination elements will appear on the page. This way, all posts will be displayed on the blog, and WordPress will automatically create as many pages as needed.

We got acquainted with only some functions for building a theme for WordPress- these are functions output of records. However, the important thing here is to understand the principle and not try to memorize or memorize it.

Practice

Let's consider output of records using the topic as an example Twenty Seventeen. Posts are displayed via the template tag get_template_part in the template loop index.php, which passes the contents of the template in parameters content.php.

if (have_posts()) :
/* Start the Loop */
while (have_posts()) :
the_post();
get_template_part("template-parts/post/content", get_post_format());
endwhile;
endif; ?>

In the template content.php The title of the post is displayed with a link to the post itself and the content.

Retrieves records (posts, pages, attachments) from the database based on the specified criteria. You can select any posts and sort them as you wish.

An array of WP_Post objects (posts). Each object in the array looks like this:

Array(=> object(WP_Post)#4692 (24) ( ["ID"] => int(822) ["post_author"] => string(1) "1" ["post_date"] => string(19) "2016-07-07 10:28:57" ["post_date_gmt"] => string(19) "2016-07-07 07:28:57" ["post_content"] => string(6225) "Article content" ["post_title"] => string(37) "Dead Sea (14 photos)" ["post_excerpt"] => string(15) "Quote about the article" ["post_status"] => string(7) "publish" [ "comment_status"] => string(4) "open" ["ping_status"] => string(4) "open" ["post_password"] => string(0) "" ["post_name"] => string(95 ) "mertvoe-more-14-foto" ["to_ping"] => string(0) "" ["pinged"] => string(0) "" ["post_modified"] => string(19) "2016- 07-07 10:28:57" ["post_modified_gmt"] => string(19) "2016-07-07 07:28:57" ["post_content_filtered"] => string(0) "" ["post_parent"] => int(0) ["guid"] => string(0) "" ["menu_order"] => int(0) ["post_type"] => string(4) "post" ["post_mime_type"] = > string(0) "" ["comment_count"] => string(1) "0" ["filter"] => string(3) "raw" ) => object(WP_Post)( ... ) => object (WP_Post)( ... ))

Usage

get_posts($args);

Usage pattern

// default parameters $posts = get_posts(array("numberposts" => 5, "category" => 0, "orderby" => "date", "order" => "DESC", "include" => array (), "exclude" => array(), "meta_key" => "", "meta_value" =>"", "post_type" => "post", "suppress_filters" => true, // suppress change filters SQL query)); foreach($posts as $post)( setup_postdata($post); // output format the_title() ... ) wp_reset_postdata(); // reset $args (string/array) List of arguments according to which the result will be obtained.
Default: Preset

$args Parameter Arguments

As of WordPress 2.6, in addition to the parameters described below, get_posts() can accept all the same parameters as WP_Query.

In get_posts(), the suppress_filters parameter is enabled by default, which is disabled in query_posts() and WP_Query - i.e. there filters work. Enabling suppress_filters suppresses all SQL query change filters of the following type: posts_* or comment_feed_* .

suppress_filters does not affect the operation of the pre_get_posts filter - it will work regardless of what is specified in suppress_filters .

This disabling of filters by default can be confusing if there are plugins that affect the output of records through SQL query filters, for example WPML. In such cases, suppress_filters should be disabled.

The "category" parameter needs to be passed the ID, not the name of the category. You can also pass the string “category”: ID separated by commas.

numberposts (number) Number of posts displayed. Set to 0 to limit output to the maximum number of posts per page (set in the VI settings) or set to -1 to remove output restrictions (LIMIT).
Default: 5 offset (number) Indentation from the first post (entry). category (number/string/array)

Which categories to display posts from? Specify the ID of the category from which you want to get posts or specify -3 instead of 3 if you want to get all posts except posts from category 3 (exclude category). You can specify multiple IDs separated by commas ("3,5,12" or "-3,-5,-12").

See the description of the cat parameter of WP_Query.

In the WP_Query and query_posts() functions, this parameter is disabled by default (equal to false).
Default: true

Examples

#1. Displaying posts with indentation

If you have one, last post displayed on the main page, but you need to display 5 more previous ones from category 1, then you can use the following code:

    5, "offset"=> 1, "category" => 1); $myposts = get_posts($args); foreach($myposts as $post)( setup_postdata($post); ?>
  • ">

#2. Displaying posts with indentation, without breaking the main loop.

If the get_posts() function was used and after it you need to use the standard WordPress loop, then you need to save the global $post variable, do it like this:

    5, "offset"=> 1, "category" => 1); $myposts = get_posts($args); foreach($myposts as $post)( setup_postdata($post); ?>
  • ">

#3. Ability to use special VI Loop functions

By default, in a loop based on get_posts() it is impossible to use, for example, the_content() or the_date() function. This problem is solved by the setup_postdata() function, which needs to pass the $post variable:

3); $lastposts = get_posts($args); foreach($lastposts as $post)( setup_postdata($post); // set the data?>

">

Data can also be obtained by accessing an object's property (object->object_property). For example, for this example $post->ID will be equal to the post ID, $post->post_content will contain the content of the post. The object property is a column of the database table posts. The names of the columns can be viewed.

Don't forget that data is displayed on the screen using the php echo operator:

ID; ?>

#4. Latest posts sorted by title

We will get the latest posts sorted by title in alphabetical order. The following example will output the date, title, and quote of the post:

10, "order"=> "ASC", "orderby" => "title")); foreach ($postslist as $post)( setup_postdata($post); ?>


#5. Random posts

Let's get 5 random posts, implemented using the "orderby" => "rand" parameter:

    5, "orderby" => "rand"); $rand_posts = get_posts($args); foreach($rand_posts as $post) : ?>
  • ">

#6. Get all attached files

Used outside of the WordPress Loop. The following code will display the title, link, and quote of the attached file:

"attachment", "posts_per_page" => -1, "post_status" => null, "post_parent" => null); $attachments = get_posts($args); if ($attachments) ( foreach ($attachments as $post) ( setup_postdata($post); the_title(); the_attachment_link($post->ID, false); the_excerpt(); ) ) wp_reset_postdata(); ?>

#7. Attached files for a specific post

The code needs to be used inside a WordPress Loop, where the $post->ID variable is:

"attachment", "posts_per_page" => -1, "post_status" => null, "post_parent" => $post->ID); $attachments = get_posts($args); if ($attachments) ( foreach ($attachments as $attachment) ( echo apply_filters("the_title" , $attachment->post_title); the_attachment_link($attachment->ID , false); ) ) wp_reset_postdata(); ?>

#8. Latest posts from the same category

We will display a list of the latest posts of the current category in which the post is located. In this case, we will exclude the current record:

term_id; $real_id = get_the_ID(); $args = array("cat" =>$cat_add_id); $posts = get_posts($args); foreach($posts as $post)( setup_postdata($post); if ($post->ID<>$real_id)( ?> ">

Notes

    Since version 2.6, a number of transmitted values ​​for the orderby parameter have been changed - the post_ prefix has been removed, for example, there was post_title, it became just title.

  • Since version 3.0, arrays of IDs can also be passed to the include and exclude parameters.

Do you want to buy cheap views on Instagram for a video or TV broadcast, but don’t know where? Try visiting the Doctor SMM website, where you will be offered one of the lowest prices on RuNet for views. Hurry up, as the offer is valid for a limited time! In addition, here you can very quickly purchase a resource with an optimal speed mode specifically for your page. Grow your account quickly and easily!

Notes

  • See: WP_Query::parse_query()

List of changes

From version 1.2.0 Introduced.

Code get posts: wp-includes/post.php WP 5.2.3

5, "category" => 0, "orderby" => "date", "order" => "DESC", "include" => array(), "exclude" => array(), "meta_key" => "", "meta_value" => "", "post_type" => "post", "suppress_filters" => true,); $r = wp_parse_args($args, $defaults); if (empty($r["post_status"])) ( $r["post_status"] = ("attachment" == $r["post_type"]) ? "inherit" : "publish"; ) if (! empty ($r["numberposts"]) && empty($r["posts_per_page"])) ( $r["posts_per_page"] = $r["numberposts"]; ) if (! empty($r["category" ])) ( $r["cat"] = $r["category"]; ) if (! empty($r["include"])) ( $incposts = wp_parse_id_list($r["include"]); $r["posts_per_page"] = count($incposts); // only the number of posts included $r["post__in"] = $incposts; ) elseif (! empty($r["exclude"])) ( $ r["post__not_in"] = wp_parse_id_list($r["exclude"]); ) $r["ignore_sticky_posts"] = true; $r["no_found_rows"] = true; $get_posts = new WP_Query; return $get_posts->query($r); )

Want to display your latest posts in WordPress? Displaying recent posts helps users easily find what's new on your blog. You can display the latest posts in the sidebar, inside the content using a shortcode, at the end of the post, and in the footer area or wherever you like. In this article, we will show you how to display the latest posts in WordPress using plugins, widgets, shortcodes and manually using the display recent posts feature.

Using the Recent Posts Widget

WordPress has its own widget for displaying recent posts, which can be inserted into the sidebar (sidebar) of your site, or any other ready-made area for widgets. Just go to: Appearance » Widgets and drag the widget into the widget area of ​​your site.

The widget is very simple and you can add your own title, display the post date, and set the number of posts to display.

Using the Recent Posts Widget Extended plugin

As we mentioned above, the built-in recent posts widget is quite basic and limited in use, as you won't be able to display post thumbnails and announcements, which are often a priority for most users.

What if you want to display the latest posts with thumbnails and small post announcements? What to do if you want to display recent posts from a certain category or tag?

In this case, the Recent Posts Widget Extended plugin will come in handy.

Recent Posts Widget Extended . Once activated, simply go to: Appearance » Widgets and drag the widget Recent Post Extended in the sidebar.

This widget is highly customizable and gives you full control over how you want to display the latest posts on your WordPress site. You can display thumbnails, post previews, set categories and tags, and much more. You can also use this widget to display the latest posts of a particular post type.

You can increase the font size by unchecking “use default styles” and setting your own values.

Displaying recent posts using a shortcode

Showing the latest posts in a sidebar is pretty easy, but what if you want to display the latest posts within a WordPress post or page? The most obvious and easiest way to display recent posts within a post or page is with a special shortcode.

The first thing you need to do is install and activate the Display Posts Shortcode plugin. After activation, the plugin will work immediately, there are no settings.

Open the required page or post in the WordPress editor and paste the shortcode into the desired location. There are a number of parameters you can use in the shortcode. Below are some examples:

Output of the 5 latest posts with thumbnails and announcements:

Displaying recent pages instead of posts:

Sort by name instead of date:

Outputting the latest pages from a specific parent page:

You can find the full list of parameters on the plugin documentation page.

These shortcodes can also be used inside a text widget, but first, you will need to enable shortcode support in the text widget. To do this, add the below code to your theme's function.php:

Add_filter('widget_text', 'do_shortcode');

Displaying new entries manually

More advanced users can display the latest posts manually by adding a little code to the WordPress theme files. There are several ways to do this, but the simplest way is to use the built-in WP_Query class.

Just add the below code where you want to display the latest posts.


    // Define our WP Query Parameters

    // Start our WP Query
    have_posts()) : $the_query -> the_post(); ?>

    // Display the Post Title with Hyperlink

  • »>
  • // Display the Post Excerpt

  • // Repeat the process and reset once it hits the limit
    endwhile;
    wp_reset_postdata();
    ?>

This code will display the last five posts with the title and announcement. The WP_Query class has many parameters, which means you can customize it to your liking. For more information, visit the code page.

We hope this article helped you learn how to display recent posts in WordPress.