WordPress Infinite Loop on Single Post - php

I've taken some code from https://gist.github.com/banago/5603826 so that I am able to do previous/next posts for a specific post on my WordPress site which is a custom post type of 'product'.
<?php
if( get_adjacent_post(false, '', true) ) {
previous_post_link('%link', '← Previous Post');
} else {
$first = new WP_Query('post_type=products&posts_per_page=1&order=DESC'); $first->the_post();
echo '← Previous Post';
wp_reset_query();
};
if( get_adjacent_post(false, '', false) ) {
next_post_link('%link', 'Next Post →');
} else {
$last = new WP_Query('post_type=products&posts_per_page=1&order=ASC'); $last->the_post();
echo 'Next Post →';
wp_reset_query();
};
?>
However it doesn't actually infinitely loop, if it's on the first or last post, the link outputs the page it's already on. An example can be found here - http://s860623395.websitehome.co.uk/products/bespoke-build/
Any solutions to this? Thanks!

Was just working on this myself the other day for a portfolio.
Here is what worked for me (adjusted for your product loop)
It should show a single next product indefinitely (infinite loop)
if( get_adjacent_post(false, '', true) ) {
$previous_link_url = get_permalink( get_previous_post() );
echo '← Next Product';
} else {
$first = new WP_Query('post_type=product&posts_per_page=1&order=DESC');
$first->the_post();
echo 'Next Product →';
wp_reset_query();
};
Just a note, next post is actually the previous post, It's a confusing thing, but when you view the latest post, be it portfolio, product or whatever, the next one is actually the one before, otherwise the next post after the most recent published post would then be the oldest one. This seems to be how most have done it within an infinite loop.

Like you, I tried many variations, none of which really worked, but this one did. Currently I'm using it in the Genesis framework for a portfolio CPT with a background image.
Here is the full working code below taken from a child theme:
add_action( 'genesis_after_content_sidebar_wrap', 'go_prev_next_post_nav_cpt', 999 );
/**
* Enable next link in portfolio.
*
* #since 1.0.0
*/
function go_prev_next_post_nav_cpt() {
echo '<div class="adjacent-entry-pagination">';
echo '<div class="wrap">';
if( get_adjacent_post(false, '', true) ) {
$prevThumb = get_the_post_thumbnail_url( get_previous_post(), 'full' );
$previous_link_url = get_permalink( get_previous_post() );
$prevTitle = get_the_title( get_previous_post() );
echo '<a class="post-link bg-image bg-overlay" href="' . $previous_link_url . '" style="background-image:url(' . $prevThumb . ')"><div class="next-description"><p class="mast">Next project</p><h3 class="display-2">' . $prevTitle . '</h3></div></a>';
} else {
$first = new WP_Query('post_type=portfolio&posts_per_page=1&order=DESC');
$first->the_post();
$bg_image = get_the_post_thumbnail_url();
echo '<a class="post-link bg-image bg-overlay" href="' . get_permalink() . '" style="background-image: url(' . $bg_image . ')"><div class="next-description"><p class="mast">Next project</p><h3 class="display-2">' . get_the_title() . '</h3></div></a>';
wp_reset_query();
};
echo '</div>';
echo '</div>';
}
From memory, I used this as a starting point (lot a trial and error!). https://gist.github.com/banago/5603826

Related

Wordpresss: display all categories, but if one contains only one post, display this post instead

I am still new to WordPress (and PHP) and I am trying to finalize my very first template.
Current request is to display all given (sub)categories, but if one category only has one post, it should display the post instead with an excerpt. I think I am only missing one tiny piece to complete this...
What I have so far:
<?php
if(!empty($categories)) { ?>
<!-- Display Sub-Categories and description -->
<div class="brick_list">
<?php
foreach ( $categories as $category ) {
echo '<div class="item"><h4 class="item-title">' . $category->name . '</h4><div class="item-text">' . $category->description . '</div><div class="item-link">Read more</div></div>';
}
?>
</div>
<?php }; ?>
I've searched the web for a solution of the "has only one post in category" task and found this:
if( 1 == $category[0]->count ) { ..... }
But I don't know how to include (or merge) this with my existing foreach loop.
Can anyone help?
I have edit your code a bit, I ahve added a condition to check the category count before diplying the div element.
<?php
$categories = get_categories();
if(!empty($categories)) { ?>
<!-- Display Sub-Categories and description -->
<div class="brick_list">
<?php
foreach ( $categories as $category ) {
if ( $category->count!= 1 ){
echo '<div class="item"><h4 class="item-title">' . $category->name . '</h4><div class="item-text">' . $category->description . '</div><div class="item-link">Read more</div></div>';
} else {
// display the post with excerpt
}
}
?>
</div>
<?php }; ?>
?>
Let me know if you got any issue.
I was able to solve it. And at the end it doesn't look that difficult :-D
I share it here in case someone else needs it
<?php
foreach ( $categories as $category ) {
// If there is only one post available, go directly to the post
if($category->count == 1) {
$all_posts = get_posts($category);
echo '<div class="item"><h4 class="item-title">' . get_the_title($all_posts[0]->ID) . '</h4><div class="item-text">' . wp_trim_words( get_the_content($all_posts[0]->ID), 30, '...') . '"</div></div>';
// otherwise display subcategories
} else {
echo '<div class="item"><h4 class="item-title">' . $category->name . '</h4><div class="item-text">' . wp_trim_words($category->description, 30, '...') . '</div></div>';
}
}
?>

How to display only certain categories in Wordpress

I'm working in Wordpress and implemented some PHP to display all categories on a page (by a shortcode). By clicking on a category it links to a new page displaying all posts of that very category.
How do I display only certain categories, for instance by id and/or name of the cateogry?
One post has two categories (a : A & B or A & C). So one post a always has one category A, and one category B or C.
Here's my code:
function swerft_categories( ){
ob_start();
$categories = get_categories();
echo '<div class="swerft_cat">';
foreach($categories as $category) {
echo '<div class="swerft_cat_single col-lg-3 col-md-3 col-sm-6 col-xs-12">';
echo '<div class="swerft_cat_single_inner">';
$thim_group_custom_title_bg_img = get_term_meta( $category->term_id, 'thim_group_custom_title_bg_img', true );
if ($thim_group_custom_title_bg_img) {
$image_id = $thim_group_custom_title_bg_img['id'];
if ($image_id) {
$post_thumbnail_img = wp_get_attachment_image_src( $image_id, 'full' );
echo '<img src="' . $post_thumbnail_img[0] . '" alt="' . $category->name . '" />';
}
}
echo '<h5>'. $category->name .'</h5>';
echo '<p>'. $category->description . $category->count . '<span> Seminare </span>' . '</p>';
echo '</div>';
echo '</div>';
}
echo '</div>';
return ob_get_clean();
}
add_shortcode( 'swerft_categories', 'swerft_categories' );
I tried this in the first few lines for example with no success:
function swerft_categories($args){
ob_start();
$args = array('hide_empty'=> 1,
'name' => 'B');
$categories = get_categories($args);
1) I want only one certain relation to be displayed. Let's say: only the relation of a : A & B
2) I want the count to only show the amount of posts based on the relation above.
3) By clicking on a category based on this relation, I want only those posts to be displayed of course.
I was able to find a solution for the above mentioned problem together with a colleague. See the code below, I hope it may help someone maybe; and thanks for anyone considering this task though ;)
// Function to only show individual seminars after click on category on category-page
function swerft_filter_posts_open_individual_seminare( $query ) {
$offene_seminare = isset($_GET['offene_seminare']) ? boolval($_GET['offene_seminare']) : false;
$individual_seminars_category_id = 91;
if($query->is_category() && $query->is_main_query()) {
if ($offene_seminare) {
$query->set( 'category__not_in', $individual_seminars_category_id );
} else {
$query->set( 'category__in', $individual_seminars_category_id );
}
}
}
add_action( 'pre_get_posts', 'swerft_filter_posts_open_individual_seminare' );
// Function to only count individual seminars in overview
function swerft_count_individual_seminars_in_category($category_id) {
$individual_seminars_category_id = 91;
$query_args = array(
'post_type' => 'post',
'category__and' => array($individual_seminars_category_id, $category_id)
);
$query = new WP_Query( $query_args );
$count = $query->found_posts;
return $count;
}

Create a loop for recent post with image outside wordpress

I need to create a recent posts section outside a WordPress website, but the result is incorrect (see image). I used this PHP code:
// elsewhere in code...
require "wp-load.php";
// the code that is generating the recent posts section
$posts = get_posts( array( 'posts_per_page' => 1 ) );
$recent_posts = wp_get_recent_posts(array('numberposts' => 7 ) );
foreach ($posts as $_post) {
foreach($recent_posts as $post) {
if ( has_post_thumbnail( $_post->ID ) ) {
echo '<div class="owl-item">';
echo '<figure class="blog-item-container">';
echo '<span class="blog-item-img">';
echo get_the_post_thumbnail( $_post->ID, array(480, 305) );
echo '</span>';
echo '<figcaption>';
echo '<h3>', $post['post_title'], '</h3>';
echo '</figcaption>';
echo '</figure>';
echo '</div>';
}
}
}
I was expecting to get the image for each specific recent post. This result gives to me the correct recent post, but the image is the same for all the posts. Why is the image the same?
Here's some comments on your code, which will hopefully explain what's going wrong, or help you get to the bottom of it:
// Here you are getting ONE post for some reason, and putting it in the $posts variable
$posts = get_posts( array( 'posts_per_page' => 1 ) );
// Here you are getting 7 posts, and putting in the $recent_posts variable
$recent_posts = wp_get_recent_posts(array('numberposts' => 7 ) );
// Here you are "looping" over the ONE post and putting into $_post variable.
// So here, $_post is made to reference the single most recent post
foreach ($posts as $_post) {
// Here, you are "looping" over the 7 recent posts, putting into $post variable
foreach($recent_posts as $post) {
// Here you ask if the ONE most recent post ($_post) has a featured image.
// I doubt this is what you actually want, as this will
// be run for all 7 recent posts, but is only referencing
// the single ONE post
if ( has_post_thumbnail( $_post->ID ) ) {
echo '<div class="owl-item">';
echo '<figure class="blog-item-container">';
echo '<span class="blog-item-img">';
// here you are displaying the image for the ONE post, not the 7 most recent posts
echo get_the_post_thumbnail( $_post->ID, array(480, 305) );
echo '</span>';
echo '<figcaption>';
// Here you are referencing the title, link, etc.
// for the 7 most recent posts
echo '<h3>', $post['post_title'], '</h3>';
echo '</figcaption>';
echo '</figure>';
echo '</div>';
}
}
}
So, given your question of "recent posts", and your comment that it is incorrect to show the same featured image for all of them, I suspect the code should look like this (NOTE: you can remove all of the commented code, I left it here to explain what the changes are):
// remove this - no need for the single most recent post
// $posts = get_posts( array( 'posts_per_page' => 1 ) );
$recent_posts = wp_get_recent_posts(array('numberposts' => 7 ) );
// remove this - don't loop over the single most recent post
// foreach ($posts as $_post) {
foreach($recent_posts as $post) {
// change this to $post['ID'] (from $_post->ID)
if ( has_post_thumbnail( $post['ID'] ) ) {
echo '<div class="owl-item">';
echo '<figure class="blog-item-container">';
echo '<span class="blog-item-img">';
// change this to $post['ID'] (from $_post->ID)
echo get_the_post_thumbnail( $post['ID'], array(480, 305) );
echo '</span>';
echo '<figcaption>';
echo '<h3>', $post['post_title'], '</h3>';
echo '</figcaption>';
echo '</figure>';
echo '</div>';
}
}
// remove this, since we are removing the loop
// }

wordpress blog connects with php website

I have wordpress blog and php website.
I'd like to put the information about new articles on wordpress blog to the php website.
I did something. I have titles of articles.
But I need featured images and descriptions as well.
Here is code which I put on my php website.
<?php
// connection with wordpress
$db = mysql_connect ("localhost", "...", "....");
mysql_select_db ("...", $db);
$result_redaktor = mysql_query("SELECT * FROM wp_posts WHERE post_status = 'publish' ORDER by post_date DESC LIMIT 10", $db);
if (!$result_redaktor)
{
exit (mysql_error());
}
if (mysql_num_rows($result_redaktor) > 0)
{
$myrow_redaktor = mysql_fetch_array($result_redaktor);
do
{
printf ("<div class='main'>
<a href='http://redaktor.11klassniki.ru/%s'>%s</a></div>"
, $myrow_redaktor["guid"], $myrow_redaktor["post_title"]);
}
while ($myrow_redaktor = mysql_fetch_array($result_redaktor));
}
else
{
echo "<p>no data.</p>";
exit ();
}
include ("blocks/bd.php");
?>
I don't know how to get featured image and text (lead, which goes before tag more).
P.S My site and my blog are in the same hosting.
This code allows to see titles. It works. But I need to add pictures to titles.
How can I customize next code
$thumbnails = get_posts('numberposts=10');
foreach ($thumbnails as $thumbnail) {
if ( has_post_thumbnail($thumbnail->ID)) {
echo '<a href="' . get_permalink( $thumbnail->ID ) . '" title="' . esc_attr( $thumbnail->post_title ) . '">';
echo get_the_post_thumbnail($thumbnail->ID, 'thumbnail');
echo '</a>';
}
}
echo get_the_post_thumbnail( $post_id, $size, $attr );
You should use wordpress RSS, read this article for more info:
http://www.wpbeginner.com/beginners-guide/what-is-rss-how-to-use-rss-in-wordpress/
Or, if your site and your blog are in the same hosting, you should include wp-load.php file in your php site and use all the function wordpress to show posts.
One example from http://davidwalsh.name/wordpress-recent-posts:
// Include the wp-load'er
include('wp-load.php');
// Get the last 10 posts
// Returns posts as arrays instead of get_posts' objects
$recent_posts = wp_get_recent_posts(array(
'numberposts' => 10
));
// Do something with them
echo '<ul>';
foreach($recent_posts as $post) {
echo '<li>', $post['post_title'], '</li>';
}
echo '</ul>';
Enjoy your code!

Customizing a Wordpress-generated breadcrumb link

Good Day
I am using Wordpress, and I am using a breadcrumbs plugin (Breadcrumb NavXT). Now it works great, exept that I would like to customize the way it links to a specific link:
Now here is the scenario:
I have a page, and on the page are links to posts. So when you click on one of the links on the page, it takes you to the post. Now this posts belongs to a category named Drill Rigs, and Drill Rigs is a child category of Products.
Now on the post page, which has category 'products>drill rigs' (parent/child), the breadcrumb shows the following way:
Home>products>drill rigs>postname
Problem is, that of you click on the products link above, it takes you to the category page of products:
siteurl/category/products
and not the actual wordpress page that is called products (that contains the links linking to the posts mentioned above:
siteurl/absolute link to the page, which is a unique link eg. siteurl/803-2
Now as far as I know, you cannot change the path from a category (which are unique to posts) to a page, neither in wordpress nor the plugin.
The best way I can think of is to add custom jquery or php to the posts php page (or index/header pages) that looks for the container div containing the anchor tags that hosts the title 'products'...and then replacing that anchor tag with my custom unique page url...
How would I do this...?
function the_breadcrumb() {
$sep = '/';
if (!is_front_page()) {
echo '<div class="breadcrumbs">';
echo '<a href="';
echo get_option('home');
echo '">';
bloginfo('name');
echo '</a>' . $sep;
if (is_category() || is_single() ){
the_category('title_li=');
} elseif (is_archive() || is_single()){
if ( is_day() ) {
printf( __( '%s', 'text_domain' ), get_the_date() );
} elseif ( is_month() ) {
printf( __( '%s', 'text_domain' ), get_the_date( _x( 'F Y', 'monthly archives date format', 'text_domain' ) ) );
} elseif ( is_year() ) {
printf( __( '%s', 'text_domain' ), get_the_date( _x( 'Y', 'yearly archives date format', 'text_domain' ) ) );
} else {
_e( 'Blog Archives', 'text_domain' );
}
}
if (is_single()) {
echo $sep;
the_title();
}
if (is_page()) {
echo the_title();
}
if (is_home()){
global $post;
$page_for_posts_id = get_option('page_for_posts');
if ( $page_for_posts_id ) {
$post = get_page($page_for_posts_id);
setup_postdata($post);
the_title();
rewind_posts();
}
}
echo '</div>';
}
}
try this hope this may help you
This code works with asynchron content for your posts: (to copy in functions.php)
function ariane() {
$cat_id = get_the_category()[0]->term_id;
$breadcrumb = '<li>' . get_the_title() . '</li>';
$if_parent = TRUE;
while($if_parent == TRUE) :
$cat_object = get_category($cat_id);
$cat = $cat_object->term_id;
$categoryURL = get_category_link($cat);
$name = $cat_object->name;
$cat_id = $cat_object->parent;
$add_link = '<li>' . $name . '</li>';
$breadcrumb = substr_replace($breadcrumb, $add_link, 0, 0);
if($cat_id == 0) :
$if_parent = FALSE;
endif;
endwhile;
echo '<ul>' . $breadcrumb . '</ul>';
}
In your archive.php or in the loop WP_QUERY
<div class="ariane"><?php ariane(); ?></div>
in css :
.ariane ul{
display: flex;
justify-content: flex-start;
align-items: center;
}
.ariane li:not(:last-child):after {
content: '>';
margin: 0 5px;
}
you can use the function to set your Breadcrumb by coding :
function the_breadcrumb() {
if (!is_home()) {
echo '<a href="';
echo get_option('home');
echo '">';
echo "Home";//bloginfo('name');
echo "</a> / ";
if (is_category() || is_single()) {
the_category('title_li=');
if (is_single()) {
echo " / ";
the_title();
}
} elseif (is_page()) {
echo the_title();
}
}
}
Put the above code in function.php file
you have to just call the function where you want to show the bredcrumb
<?php the_breadcrumb(); ?>
Hope this will help you ...
<script type="text/javascript">
$('#breadcrumbs .category[href="http://mysite.com/category/products"]').attr('href','http://mysite.com/803-2');
</script>
where:
http://mysite.com/803-2
is the url of the p[age I want to link to...

Categories