Wordpress - Include static image after every X post through wp_query - php

I have a somewhat complicated design.
I want to use a CPT to output it. This is my CPT in the wp_query:
/**
* Management Team Shortcode
**/
function team_query() {
$args = array(
'posts_per_page' => -1,
'post_type' => 'management-team',
'order' => 'DESC',
);
$posts = get_posts( $args );
if ( !empty( $posts ) ) {
$flag = 0;
foreach ($posts as $counter => $p) {
$counter++;
if ( $flag <= 2 ) {
$flag++;
}
$role = get_field( "role" );
$name = get_field( "team_member_name" );
$bio = get_field( "bio" );
$profile = get_the_post_thumbnail_url( $p->ID, 'full' );
$flip = get_field( "flip_content" );
$html_out = '<article class="team-member">';
// Do stuff with each post here
if ( $flag % 2 == 0 ) {
//add image after second post like
$html_out .= '<img src="http://www.ankitdesigns.com/demo/rawafid/wp-content/themes/rawafid-systems/assets/img/mt-1.jpg" alt="Safety Whistle" />';
}
if ( $counter % 6 == 0 ) {
$flag = 0;
//add image after sixth post like
$html_out .= '<img src="http://www.ankitdesigns.com/demo/rawafid/wp-content/themes/rawafid-systems/assets/img/mt-2.jpg" alt="Safety Whistle" />';
}
$html_out .= '<div class="meta-team"><h6>' . $role . '</h6>' . '<h4>' . $name . '</h4>' . '<p>' . $bio . '</p></div>';
$html_out .= '</article>';
}
} else {
// No results
$html_out = 'No Management Team Members Found.';
}
return $html_out;
}
add_shortcode( 'show_management_team', 'team_query' );
After 2 posts I'd like to add a static img and after 4 posts another static and after 2 more posts another static img, etc.
I'm open to suggestions on a better approach.
I'm trying to think of an alternative method. Maybe using Visual composer to build a grid?

Hey Darren here is the logic, I think that you can modify my functions and implement it in your code.
/**
* Management Team Shortcode
**/
function team_query() {
$args = array(
'posts_per_page' => -1,
'post_type' => 'management-team',
'order' => 'ASC',
);
$posts = get_posts( $args );
if ( !empty( $posts ) ) {
$flag = 0;
foreach ($posts as $counter => $p) {
$counter++;
if ( $flag <= 2 ) {
$flag++;
}
$title = get_the_title($p->ID);
$link = get_the_permalink($p->ID);
$featured_img = get_the_post_thumbnail_url( $p->ID, 'full' );
$html_out = '<article class="recent-project" style="background: url(' . $featured_img . ') no-repeat center center; background-size: cover;">';
// Do stuff with each post here
if ( $flag % 2 == 0 ) {
//add image after second post like
// $html .= <img src="css/images/myimage1.png" alt="" />
}
if ( $counter % 6 == 0 ) {
$flag = 0;
//add image after sixth post like
// $html .= <img src="css/images/myimage2.png" alt="" />
}
$html_out .= '<div class="container"><div class="meta-project"><h6>Latest Project</h6>' . '<h2>' . $title . '</h2>' . '<a class="btn btn-lg btn-tertiary" href="' . $link . '">' . 'Discover' . '</a></div></div>';
$html_out .= '</article>';
}
} else {
// No results
echo "Nothing to show";
}
return $html_out;
}
Cheers :)

Related

How to display an alphabetically sorted list of post withe Php (WordPress )

I would like to create a glossary overview page on wordpress via PHP, which can be used via a shortcode. I would like that always the initial letter is displayed and then the individual topics (posts) which begin with this.
Example:
A
Apple
Apricot
B
Banana
Blackberry
and so on...
To implement this I use the following code:
// get glossary
function glossary($post_id) {
$all_posts = new WP_Query(
array(
'posts_per_page' => -1,
'post_type' => 'glossar',
'orderby' => 'title',
'order' => 'ASC',
));
echo '<ul>';
if( $all_posts->have_posts()){
foreach( range( 'A', 'Z' ) as $letter ) {
echo '<div class="group_letter"><div class="letter">' . $letter. '</div>';
while( $all_posts->have_posts() ){
$all_posts->the_post();
$title = get_the_title();
$name = get_post_field( 'post_name', get_post() );
$initial = strtoupper( substr( $title, 0, 1 ) );
if( $initial == $letter ){
echo '<li><a class="glossary-listing" href="/glossar/'. $name . '">' . $title . '</a></li>';
}
}
$all_posts->rewind_posts();
}
}
echo '</ul>';
}
add_shortcode( 'glossary', 'glossary' );
So far it works, but now it shows letters for which there are no posts. This is how it looks now
I have tried to do it with an if query, but so far, I am stuck. Can someone help me?
Best regards and thank you!
Sort the array using PHP sort() function then loop through the result
<?PHP
$list=['apples','popsicles','Zinger','donkeys','bananas','joe',
'Locusts','gazelles','Angels','Popsicle','Dongle','jump','cocoa'
];
//convert all elements to same case
//sorting will sort by case
$list =array_map('strtolower', $list);
//sort the array
sort($list);
$last_letter=null;
foreach($list as $item){
$current_letter=substr($item,0,1);
if($last_letter!=$current_letter){
?>
<div style="margin:1rem;padding:1rem;background:#f5f5f5;">
<?=$current_letter?>
</div>
<?php
$last_letter=$current_letter;
}
?>
<div style="margin:1rem;padding:1rem;background:#f5f5f5;">
<?=$item?>
</div>
<?PHP
}
?>
I am sure there is a better solution besides running 26 times through the while loop. Anyway, here is what you are looking for.
// get glossary
function glossary($post_id) {
$all_posts = new WP_Query(
[
'posts_per_page' => -1,
'post_type' => 'glossar',
'orderby' => 'title',
'order' => 'ASC',
]
);
echo '<ul>';
if ($all_posts->have_posts()) {
foreach (range('A', 'Z') as $letter) {
$foundPostable = false;
while ($all_posts->have_posts()) {
$all_posts->the_post();
$title = get_the_title();
$name = get_post_field( 'post_name', get_post() );
$initial = strtoupper(substr($title, 0, 1));
if ($initial === $letter) {
if ($foundPostable === false) {
$foundPostable = true;
echo '<div class="group_letter"><div class="letter">' . $letter. '</div>';
}
echo '<li><a class="glossary-listing" href="/glossar/'. $name . '">' . $title . '</a></li>';
}
}
$all_posts->rewind_posts();
}
}
echo '</ul>';
}
add_shortcode( 'glossary', 'glossary' );
As for improvement, something like this might work as well.
// get glossary
function glossary($post_id) {
$all_posts = new WP_Query(
[
'posts_per_page' => -1,
'post_type' => 'glossar',
'orderby' => 'title',
'order' => 'ASC',
]
);
echo '<ul>';
$startLetter = '';
while ($all_posts->have_posts()) {
$all_posts->the_post();
$title = get_the_title();
$name = get_post_field( 'post_name', get_post() );
$initial = strtoupper(substr($title, 0, 1));
if ($initial !== $startLetter) {
$startLetter = $initial
echo '<div class="group_letter"><div class="letter">' . $letter . '</div>';
}
echo '<li><a class="glossary-listing" href="/glossar/'. $name . '">' . $title . '</a></li>';
}
echo '</ul>';
}
add_shortcode('glossary', 'glossary');

How to show categories and date on posts

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.

shortcode get all posts [ showing post's categories issues ]

I try to do a shortcode to get all posts by following this link
My shortcode code put in child theme's functions.php file.:-
function myprefix_custom_grid_shortcode( $atts ) {
$atts = shortcode_atts( array(
'posts_per_page' => '-1',
'term' => '',
), $atts, 'myprefix_custom_grid' );
extract( $atts );
$output = '';
$query_args = array(
'post_type' => 'post', // Change this to the type of post you want to show
'posts_per_page' => $posts_per_page,
);
if ( $term ) {
$query_args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'ID',
'terms' => $term,
),
);
}
// Query posts
$custom_query = new WP_Query( $query_args );
if ( $custom_query->have_posts() ) {
$output .= '<ul class="yj-trainingcamp-list clearfix">';
while ( $custom_query->have_posts() ) {
$custom_query->the_post();
$categories = get_the_category();
$separator = ' ';
$output_cats = '';
if($categories){
foreach($categories as $category) {
$output_cats .= ''.$category->cat_name.''.$separator;
}
}
$output .= '<li class="yj-trainingcamp-item">
<a href="' . get_permalink() . '" title="' . get_the_title() . '" class="trainingcamp-atom-wrap" target="_blank">
<div class="cover-img-zone">
<div class="el-image cover-img"><img src="' .get_the_post_thumbnail_url($post->ID, 'full'). '" alt="" class="el-image__inner" style="object-fit: cover;"></div></div><div class="infos"><div class="camp-info"><div class="camp-name"><span class="camp-num">第10期</span>' . get_the_title() . '</div>
<div class="nums"><div class="sale-count">' .get_the_excerpt(). ' ' . trim($output_cats, $separator) . ' </div>
</div>
</div>
<div class="teacher-info">
<div class="teacher-img-zone">
<div class="el-image teacher-img">' . get_avatar( get_the_author_meta('user_email') , 32 ) . '
</div>
</div>
<div class="teacher-name">作者: ' .get_the_author(). ' | ' .get_the_modified_time('M j, Y'). '</div>
</div>
</div>
</a>
</li>';
}
$output .= '</ul>';
wp_reset_postdata();
}
return $output;
}
add_shortcode( 'myprefix_custom_grid', 'myprefix_custom_grid_shortcode' );
Here's the issue showing multiple div
wanna display post's categories'name and categories'link ( foreach ) in each post but doesn't works...
Below is the part I doubt...
$categories = get_the_category();
$separator = ' ';
$output_cats = '';
if($categories){
foreach($categories as $category) {
$output_cats .= ''.$category->cat_name.''.$separator;
}
}
not really sure right now, because I cannot debug it and I am not able to read the text on the picture but as described in the wordpress the documentation, you can set the post id for the function:
get_the_category( int $id = false )
A small example from the page:
Get the Post Categories From Outside the Loop
Therefore, I would suggest, that you can add the post ID to get_the_category like this:
$categories = get_the_category(get_the_ID());
$separator = ' ';
$output_cats = '';
if($categories){
foreach($categories as $category) {
$output_cats .= ''.$category->cat_name.''.$separator;
}
}
Otherwise, I guess, the foreach loop adds all categories (name and links) to each post because you are interating over all published categories.

Pulling featured image as a background on Wordpress

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 ()

List pages and display subtitle

I've been trying to display the subtitle for each children page of the current parent page. At the moment i've got it working so that it shows all the title's of the children pages.
Basically I want it to show the subtitle underneath each title of the children pages.
// Get childern
$children = ($post->post_parent) ? wp_list_pages('title_li=&child_of='.$post->post_parent.'&echo=0') : wp_list_pages('title_li=&child_of='.$post->ID.'&echo=0');
// Set subtitle
$subtitle = get_the_title($post->the_subtitle);
echo $children;
echo $subtitle;
Any help will be much appreciated.
Cheers
You have two options for this:
1. The OOP approach
Extend the Walker_page class to create a custom iterator to use with wp_list_pages().
Add this to your functions.php:
class Subtitle_walker extends Walker_page {
function start_el(&$output, $page, $depth, $args, $current_page) {
if ( $depth )
$indent = str_repeat("\t", $depth);
else
$indent = '';
extract($args, EXTR_SKIP);
$css_class = array('page_item', 'page-item-'.$page->ID);
if ( !empty($current_page) ) {
$_current_page = get_page( $current_page );
_get_post_ancestors($_current_page);
if ( isset($_current_page->ancestors) && in_array($page->ID, (array) $_current_page->ancestors) )
$css_class[] = 'current_page_ancestor';
if ( $page->ID == $current_page )
$css_class[] = 'current_page_item';
elseif ( $_current_page && $page->ID == $_current_page->post_parent )
$css_class[] = 'current_page_parent';
} elseif ( $page->ID == get_option('page_for_posts') ) {
$css_class[] = 'current_page_parent';
}
$css_class = implode( ' ', apply_filters( 'page_css_class', $css_class, $page, $depth, $args, $current_page ) );
//Added subtitle support
$output .= $indent . '<li class="' . $css_class . '">' . $link_before . apply_filters( 'the_title', $page->post_title, $page->ID ) . $link_after . get_the_post_thumbnail($page->ID, array(72,72)) .''.' <span class="subtitle">'.get_the_subtitle($page->ID,'','',0).'</span>';
if ( !empty($show_date) ) {
if ( 'modified' == $show_date )
$time = $page->post_modified;
else
$time = $page->post_date;
$output .= " " . mysql2date($date_format, $time);
}
}
}
And call it in your template file:
$subtitle_menu = new Subtitle_walker();
$args = array(
'title_li' => '',
'child_of' => ($post->post_parent) ? $post->post_parent : $post->ID,
'echo' => 0,
'walker' => $subtitle_menu
);
$children = wp_list_pages($args);
echo $children;
Note: the previous code is based on this tutorial, you can read it to get an in-depth explanation of what it's doing
2. Using custom WP_Query loop
You can use get_page_children to query the child pages and then loop through them and build/echo your custom list items:
//Set up the objects needed
$my_wp_query = new WP_Query();
$all_wp_pages = $my_wp_query->query(array('post_type' => 'page'));
//Get children
$children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages );
//Build custom items
foreach($children as $child){
echo '<li class="page-item">';
echo ''.get_the_title($child->ID).'<br/>';
echo '<span class="subtitle">'.get_the_subtitle($child->ID).'</span>';
echo '</li>';
}

Categories