I want to categorise posts and show them on my WordPress website. So in order to achieve that I've written a code. My code is below.
function wpb_postsbycategory() {
// the query
$the_query = new WP_Query( array(
'category_name' => 'travel',
'posts_per_page' => 5
) );
// The Loop
if ( $the_query->have_posts() ) {
$string .= '<ul class="postsbycategory widget_recent_entries">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
if ( has_post_thumbnail() ) {
$string .= '<li>';
$string .= '' . get_the_post_thumbnail($post_id, array( 50, 50) ) . get_the_title() .'</li>';
} else {
// if no featured image is found
$string .= '<li>' . get_the_title() .'</li>';
}
}
} else {
// no posts found
$string .= '<li>No Posts Found</li>';
}
$string .= '</ul>';
return $string;
/* Restore original Post Data */
wp_reset_postdata();
}
// Add a shortcode
add_shortcode('categoryposts', 'wpb_postsbycategory');
This code works perfectly fine. However, I want to show posts meta descriptions as well (i.e post created date and the category). How would I achieve that? Right now It only extracts the post heading and the image. Thanks so much for helping me out.
Try this:
function wpb_postsbycategory() {
// the query
$the_query = new WP_Query( array(
'category_name' => 'travel',
'posts_per_page' => 5
) );
// The Loop
if ( $the_query->have_posts() ) {
$string .= '<ul class="postsbycategory widget_recent_entries">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$string .= '<li>';
$string .= '<a href="' . get_the_permalink() .'" rel="bookmark">';
if ( has_post_thumbnail() ) {
$string .= get_the_post_thumbnail($post_id, array( 50, 50) );
}
// title
$string .= get_the_title();
// date
$string .= get_the_date();
// categories
$categories = get_the_category();
$category_list = join( ', ', wp_list_pluck( $categories, 'name' ) );
$string .= wp_kses_post( $category_list );
// close link
$string .= '</a></li>';
}
// no posts found
$string .= '<li>No Posts Found</li>';
}
$string .= '</ul>';
return $string;
/* Restore original Post Data */
wp_reset_postdata();
}
// Add a shortcode
add_shortcode('categoryposts', 'wpb_postsbycategory');
I guess you need/want to add HTML tags around date and category.
For example:
$string .= '<span class="date">'.get_the_date().'</span>';
But that's up to you.
You can change the output of the categories based on the docs here.
Related
I am fairly new to WP functions so hoping someone could shed some light on this issue. I have a function that displays five posts from a specific category, then using a shortcode to display the results on certain WP posts/pages. I am having trouble to include wp_trim_words to get_the_title(). I want to limit the title to 5 words and end with "...". I saw many examples in here but none that would fit into my function. Can anyone help please?
function wpb_postsbycategory() {
// the query
$the_query = new WP_Query( array( 'category_name' => '3dgames', 'posts_per_page' => 5 ) );
// The Loop
if ( $the_query->have_posts() ) {
$string .= '<ul class="postsbycategory widget_recent_entries">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
if ( has_post_thumbnail() ) {
$string .= '<p>' . get_the_post_thumbnail($post_id, array( 100, 50) ) . get_the_title() .'<br></p>';
} else {
// if no featured image is found
$string .= '<li>' . get_the_title() .'</li>';
}
}
} else {
// no posts found
}
$string .= '</ul>';
return $string;
/* Restore original Post Data */
wp_reset_postdata();
}
// Add a shortcode
add_shortcode('3dgames', 'wpb_postsbycategory');
// Enable shortcodes in text widgets
add_filter('widget_text', 'do_shortcode');
You should use wp_trim_words() and inside place the title for the post:
wp_trim_words(get_the_title(), 5, '...')
In your case it should be something like this:
if ( has_post_thumbnail() ) {
$string .= '<p>' . get_the_post_thumbnail($post_id, array( 100, 50) ) . (wp_trim_words(get_the_title(), 5, '...')) .'<br></p>';
} else {
// if no featured image is found
$string .= '<li>' . (wp_trim_words(get_the_title(), 5, '...')) .'</li>';
}
For more details on how wp_trim_words() works you could visit the official documentation: https://developer.wordpress.org/reference/functions/wp_trim_words/
I need to separate posts from WP_Query into 2 columns: first post will go to right column, 3 other posts will go to left column so the structure will look like this - https://prnt.sc/vc044d
Please help me to improve my code.
Thanks a lot.
function mk_latestposts() {
// the query
$the_query = new WP_Query( array( 'posts_per_page' => 4 ) );
// The Loop
if ( $the_query->have_posts() ) {
$postcount = 0;
$string .= '<ul class="mk-recent-posts-list">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$postcount++;
// if this is the first post
if ( $postcount == 1 ) {
$string .= '<li class="first-post">';
$string .= '' . get_the_post_thumbnail($post_id, array( 50, 50) ) . get_the_title() . get_the_date() .'</li>';
} else {
// if this is the next post
$string .= '<li class="next-post">';
$string .= '' . get_the_post_thumbnail($post_id, array( 50, 50) ) . get_the_title() . get_the_date() .'</li>';
}
}
} else {
// no posts found
}
$string .= '</ul>';
return $string;
/* Restore original Post Data */
wp_reset_postdata();
}
// Add a shortcode
add_shortcode('mklatestposts', 'mk_latestposts');
Your code is fine You can do this with CSS. Just add a common class to every <li> Like <li class='single-post'> and then apply this CSS. You can change it from List structure to Div structure whatever you want.
li.single-post{ width: 47%; float: left;} ul.mk-recent-posts-list { width: 100%; }
Hey guys I have a code which rendered 5 recent posts from a specific category. Here is that
function postsbycategory() {
// the query
$the_query = new WP_Query( array( 'category_name' => 'news', 'posts_per_page' => 5 ) );
// The Loop
if ( $the_query->have_posts() ) {
$string .= '<ul class="postsbycategory widget_recent_entries">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
if ( has_post_thumbnail() ) {
$string .= '<li>';
$string .= '' . get_the_post_thumbnail($post_id, array( 50, 50) ) . get_the_title() .'</li>';
} else {
// if no featured image is found
$string .= '<li>' . get_the_title() .'</li>';
}
}
} else {
// no posts found
}
$string .= '</ul>';
return $string;
What i wated is that above code display recent posts from specific category from 1 to 5 but i want to display recent posts from 2 to 6. For better understadings focus on this e.g.
Suppose i have a category named Pizza and in that category I have 10 posts named
Post 1
Post 2
Post 3
Post 4
Post 5
Post 6
Post 7
Post 8
Post 9
Post 10
So if I apply above code to my homepage it will display post from category Pizza are
Post 1
Post 2
Post 3
Post 4
Post 5
but i want this
Post 2
Post 3
Post 4
Post 5
Post 6
Yes i want that code to start showing posts from 2 not from 1. So how to do this.
Please help me I am not a web developer.
Just add a counter ($i) in the loop and pull the first 6 posts, skipping the first one using the counter to check.
function postsbycategory() {
// the query
$the_query = new WP_Query( array( 'category_name' => 'news', 'posts_per_page' => 6 ) );
$i=1;
// The Loop
if ( $the_query->have_posts() ) {
$string .= '<ul class="postsbycategory widget_recent_entries">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
if($i>1){
if ( has_post_thumbnail() ) {
$string .= '<li>';
$string .= '' . get_the_post_thumbnail($post_id, array( 50, 50) ) . get_the_title() .'</li>';
} else {
// if no featured image is found
$string .= '<li>' . get_the_title() .'</li>';
}
}
++$i;
}
} else {
// no posts found
}
$string .= '</ul>';
return $string;
}
I'm trying to figure out how to pull the featured post image as a background (on Wordpress) but cannot get it to work.
See below the code I'm using. $thumbimg should be pulling the featured image but obviously i am doing something wrong there.
$lessons = get_posts( $args );
if( count( $lessons ) > 0 ) {
$html .= '<section class="module-lessons">';
$html .= '<header><h3>' . __( 'Lessons', 'sensei_modules' ) . '</h3></header>';
$thumbimg = wp_get_attachment_image_src( get_post_thumbnail_id($lesson->ID), array( 200,200 ), false, '' );
$html .= '<ul>';
foreach( $lessons as $lesson ) {
$html .= '<li class="lesson-items" style="background: url(<?php echo $thumbimg[0]; ?>)>';
$html .= '' . get_the_title( intval( $lesson->ID ) ) . '';
$html .= '</li>';
// Build array of displayed lesson for exclusion later
$displayed_lessons[] = $lesson->ID;
}
$html .= '</ul>';
$html .= '</section>';
}
I cannot also seem to get the style="background.." to read the php as I would like to.
It will not work because you are getting the ID wrong. The code for the thumbnail should be something like:
wp_get_attachment_image_src( get_post_thumbnail_id($post_ID), 'large' ) ;
you are doing it right except for the fact that you are calling the $lesson->ID on an object $lesson that doesn't exist outside of the loop after it :)
Editing your code:
$lessons = get_posts( $args );
if( count( $lessons ) > 0 ) {
$html .= '<section class="module-lessons">';
$html .= '<header><h3>' . __( 'Lessons', 'sensei_modules' ) . '</h3></header>';
$html .= '<ul>';
foreach( $lessons as $lesson ) {
// This should be inside the loop
$thumbimg = wp_get_attachment_image_src( get_post_thumbnail_id($lesson->ID), array( 200,200 ), false, '' );
$html .= '<li class="lesson-items" style="background-image: url("'. $thumbimg[0] . '")>';
$html .= '' . get_the_title( intval( $lesson->ID ) ) . '';
$html .= '</li>';
// Build array of displayed lesson for exclusion later
$displayed_lessons[] = $lesson->ID;
}
$html .= '</ul>';
$html .= '</section>';
}
As for the background in CSS, use background-image: url ()
I am creating a shortcode to display the most recent posts in the homepage, however I cannot get the pagination working.
When you click on 'older posts' the page refreshes but the same 2 original posts are displayed.
if ( ! function_exists('vpsa_posts_shortcode') ) {
function vpsa_posts_shortcode( $atts ){
$atts = shortcode_atts( array(
'per_page' => 2,
'order' => 'DESC',
'orderby' => 'date'
), $atts );
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'post',
'posts_per_page' => $atts["per_page"],
'order' => $atts["order"],
'orderby' => $atts["orderby"],
'paged' => $paged
);
$query = new WP_Query($args);
if($query->have_posts()) : $output;
while ($query->have_posts()) : $query->the_post();
$output .= '<article id="post-' . get_the_ID() . '" class="' . implode(' ', get_post_class()) . '">';
$output .= '<h4 class="post-title"><span>' . the_title('','',false) . '</span></h4>';
$output .= '<div class="row">';
$output .= '<div class="col-md-3">';
$output .= '<a href="' . get_permalink() . '" title="' . the_title('','',false) . '">';
if ( has_post_thumbnail() ) {
$output .= get_the_post_thumbnail( get_the_id(), 'featured', array('class' => 'img-responsive aligncenter'));
} else {
$output .= '<img class="img-responsive aligncenter" src="' . get_template_directory_uri() . '/images/not-available.png" alt="Not Available" height="150" width="200" />';
}
$output .= '</a>';
$output .= '</div>';
$output .= '<div class="col-md-9">';
$output .= get_the_excerpt();
$output .= '<span class="post-permalink">Read More</span>';
$output .= '</div>';
$output .= '</div>';
$output .= '<div class="post-info">';
$output .= '<ul>';
$output .= '<li>Posted: ' . get_the_time("F j, Y") . '</li>';
$output .= '<li>By: ' . get_the_author() . '</li>';
$output .= '<li>Categories: ' . get_the_category_list(", ") . '</li>';
$output .= '</ul>';
$output .= '</div>';
$output .= '</article>';
endwhile;
$output .= '<div class="post-nav">';
$output .= '<div class="prev-page">' . get_previous_posts_link( "« Newer Entries" ) . '</div>';
$output .= '<div class="next-page">' . get_next_posts_link( "Older Entries »", 3 ) . '</div>';
$output .= '</div>';
else:
$output .= '<p>Sorry, there are no posts to display</p>';
endif;
wp_reset_postdata();
return $output;
}
}
add_shortcode('vpsa_posts', 'vpsa_posts_shortcode');
You need to call paginate function.Try following code:
if ( ! function_exists('vpsa_posts_shortcode') ) {
function vpsa_posts_shortcode( $atts ){
$atts = shortcode_atts( array(
'per_page' => 2,
'order' => 'DESC',
'orderby' => 'date'
), $atts );
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'post',
'posts_per_page' => $atts["per_page"],
'order' => $atts["order"],
'orderby' => $atts["orderby"],
'paged' => $paged
);
$query = new WP_Query($args);
if($query->have_posts()) : $output;
while ($query->have_posts()) : $query->the_post();
$output .= '<article id="post-' . get_the_ID() . '" class="' . implode(' ', get_post_class()) . '">';
$output .= '<h4 class="post-title"><span>' . the_title('','',false) . '</span></h4>';
$output .= '<div class="row">';
$output .= '<div class="col-md-3">';
$output .= '<a href="' . get_permalink() . '" title="' . the_title('','',false) . '">';
if ( has_post_thumbnail() ) {
$output .= get_the_post_thumbnail( get_the_id(), 'featured', array('class' => 'img-responsive aligncenter'));
} else {
$output .= '<img class="img-responsive aligncenter" src="' . get_template_directory_uri() . '/images/not-available.png" alt="Not Available" height="150" width="200" />';
}
$output .= '</a>';
$output .= '</div>';
$output .= '<div class="col-md-9">';
$output .= get_the_excerpt();
$output .= '<span class="post-permalink">Read More</span>';
$output .= '</div>';
$output .= '</div>';
$output .= '<div class="post-info">';
$output .= '<ul>';
$output .= '<li>Posted: ' . get_the_time("F j, Y") . '</li>';
$output .= '<li>By: ' . get_the_author() . '</li>';
$output .= '<li>Categories: ' . get_the_category_list(", ") . '</li>';
$output .= '</ul>';
$output .= '</div>';
$output .= '</article>';
endwhile;global $wp_query;
$args_pagi = array(
'base' => add_query_arg( 'paged', '%#%' ),
'total' => $query->max_num_pages,
'current' => $paged
);
$output .= '<div class="post-nav">';
$output .= paginate_links( $args_pagi);
// $output .= '<div class="next-page">' . get_next_posts_link( "Older Entries »", 3 ) . '</div>';
$output .= '</div>';
else:
$output .= '<p>Sorry, there are no posts to display</p>';
endif;
wp_reset_postdata();
return $output;
}
}
add_shortcode('vpsa_posts', 'vpsa_posts_shortcode');
WP_Query with pagination inside a shortcode
Here I will show you how to create a [shortcode] containing a custom new WP_Query with pagination links.
To create a [shortcode] with a new WP_Query post loop with pagination links built in to turn any is_singular() page or single post into a custom archive based on the WP_Query arguments you set. Lets call it [wp_query_pagination_inside_shortcode], so we add with the following add_shortcode() in functions.php.
Or in my case I create separate /functions/ folder for files to stay organized with the appropriates names and have a require_once include file structure.
root/functions.php ->
require_once 'functions/shortcode-wp-query-pagination-inside-shortcode.php';
root/functions/shortcode-wp-query-pagination-inside-shortcode.php->
add_shortcode('wp_query_pagination_inside_shortcode', 'my_shortcode_function_tag');
if (!function_exists('my_shortcode_function_tag')) {
function my_shortcode_function_tag($atts)
{
ob_start(); // Turn output buffering on, helps with complicated template and theme structures
// Note: https://developer.wordpress.org/reference/functions/get_query_var/#used-by
// Custom query_vars translates to Getting an "archive" on any current page that contains a query with corresponding pagination number in the url
// example.com/page-shortcodes-on/page/2/ ...etc see below how to manipulate this
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$atts = shortcode_atts(
array(
'post_type' => 'post',
// Set attributes here you want in your shortcode
// like [shortcode post_types="post"]
),
$atts
);
// set up the default args you wont change and the ones you will by accessing the value of $atts passed into the shortcode function from your WYSIWYG content editor
$args = array(
'posts_per_page' => 3,
'paged' => $paged, // Important to receive page data
'post_type' => $atts['post_type'], // This is how you get the values of your shortcode attributes passed in
'orderby' => 'date',
'order' => 'DESC',
);
$the_query = new WP_Query($args);
// Da loop
// match your themes loop structure this below is just boiler plate stuff ignore or use your choice its not important how you create the post loop, just do it
if ($the_query->have_posts()) {
while ($the_query->have_posts()) {
$the_query->the_post();
get_template_part('template-parts/loop');
} //end while
} // endif
$big = 999999999; // need an unlikely integer for how many pages are possible
// I've tested example.com/page-shortcodes-on/page/999999999999999999/ and the custom query_var still works
echo paginate_links(
array(
'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))), // referrence the url
'format' => '?paged=%#%', // used for replacing the page number
'current' => max(1, get_query_var('paged')), // grabs the page data
'total' => $the_query->max_num_pages //$the_query is your custom query
)
);
return ob_get_clean(); // Silently discard the buffer contents
wp_reset_query(); // Lets go back to the main_query() after returning our buffered content
}
}
In a WYSIWYG Content editor in pages or posts content editor
[wp_query_pagination_inside_shortcode post_type="posts"]
URL structure for this query_var 'paged'
example.com/page-shortcode-is-on/page/2/
You will need to stylize the pagination links a bit to be acceptable but this should give you a highly useful tool to build custom WP_Query loops with multiple different post_types from anywhere in your site through your WYSIWYG editor. Add more attributes to really make this thing valuable.
// Ignore below, these are just possible search queries for this issue
WP_Query pagination inside a shortcode / add_shortcode with pagination / shortcode with custom attributes / Paginated custom post type wp_query shortcode / custom post type wp_query archive posts per page / page / pagination wont work