When I am writing below code for recent posts and then after I write code for next and previous link then that function will give me same link of post. If I am comment out "$tags = wp_get_post_tags($post->ID);" This line then It'll print next post link. How can I resolved this error ? please help me.
<?php
//for use in the loop, list 5 post titles related to first tag on current post
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo '<div class="articlecontent font16 bold fontgray">Related Posts</div>';
$first_tag = $tags[0]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'showposts'=>5,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<div class="articlecontent"><ul>';
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li><?php the_title(); ?></li>
<?php
endwhile;
echo "</ul></div>";
}
}
?>
<div class="nextprevbar">
<div class="prevtopic"><?php
previous_post_link( '%link', '<img border="0" alt="" src="'.get_template_directory_uri().'/images/prev-bullet.gif">' . _x( ' ', 'Previous post link', 'twentyten' ) . ' %title' ); ?></div>
<div class="nexttopic"><?php next_post_link( '%link', '%title <img border="0" alt="" src="'.get_template_directory_uri().'/images/next-bullet.gif">' . _x( ' ', 'Next post link', 'twentyten' ) . '</span>' ); ?></div>
</div>
The problem has to be in the $post variable. Before this line is executed:
while ($my_query->have_posts()) : $my_query->the_post(); ?>
the $post var holds the current post data (I guess this code is inside single.php?). But after this line, and inside the loop, the $post var holds your various recent posts, one by one (you setup the $post variable when you call the_post() ).
After that loop (bellow the endwhile), $post will hold the data of the last post retrieved in that loop.
previous_post_link() and next_post_link() need to access $post for reference of the current post, but they are taking as reference the last post of your recent posts, instead of the post being read by your user.
I don't know what the html structure of this page is, but I would put the recent posts list AFTER the navigation links (next, previous posts). That would solve the problem if I am right, and in my opinion it would be semantically clearer.
Or you could also try this:
Add this line:
$currentPost = clone $post;
Before:
$my_query = new WP_Query($args);
And add this line:
<?php $post = $currentPost; ?>
Before you call next and previous post links functions.
Related
Thanks for taking an intrest
I am looking for some to provide a clear, good practice, example (or link to an existing one) of how to create an A to Z list of posts with Pagination for Custom Post Type in the latest version of Wordpress based on the scenario below.
There are two existing questions I have found on this site but neither answer the question clearly or definitively.
To keep things simple for me to explain the scenario and for those responding. I am basing my explanation around a website all about Fruit. When trying to use the answers given I am hoping this will be easy for I and other learners to follow the replys and intergrate it into their own code.
Basic Structure
I have created a Custom Post Type called "Fruits".
I have created a series of Posts within Fruits, each with a Post Title
of a particular fruit e.g. "Bananas".
I have created a Page Template within which is the following div:<div id="MyAtoZArea" class="MyAtoZStyle"></div>.
Output
Within the div I would like code that will display a list of all the
posts in the custom post type "Fruits".
I would like to wrap the output in an unordered list <ul> with each title being a different list item <li>
I would like the list to be sorted alphabetically by the Post Title.
As each letter of the Alphabet changes I would like it to be inserted. For example:
A
Apples
Apricots
B
Bananas
I would like for letters of the alphabet not to be shown if there are no applicable posts. For example:
A
Apples
K
Kiwi
S
Strawberrys
Finally I would like to show a maximum of 20 posts, using pagination to show the next 20 and so on.
Can you help? If so post below.
All constructive guidance and comments are welcome.
I would do it like below. The following code you should post in your template:
<?php
//get the posts first
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'paged' => $paged,
'posts_per_page' => 20,
'post_type' => 'fruits',
'post_status' => 'publish',
'orderby' => 'title'
);
$fruits = new WP_Query( $args );
?>
<ul>
<?php
//loop through all the posts in the custom query
if( $fruits->have_posts() ) {
$current_first_letter = '';
while($fruits->have_posts() ) {
$fruits->the_post();
$title = the_title();
if (is_string($title)) {
$first_letter = $title[0]
//output a first letter list item with a custom class to be styled differently in your css if it is a new first letter
if ($first_letter != $current_first_letter) {
echo '<li class="divider"'> . strtoupper($first_letter) . '</li>';
$current_first_letter = $first_letter;
}
}
?>
<li><?php the_title(); ?></li>
<?php
}
}
?>
</ul>
//pagination
<?php if ($fruits->max_num_pages > 1) { // check if the max number of pages is greater than 1 ?>
<nav class="prev-next-posts">
<div class="prev-posts-link">
<?php echo get_next_posts_link( 'Older Entries', $fruits->max_num_pages ); // display older posts link ?>
</div>
<div class="next-posts-link">
<?php echo get_previous_posts_link( 'Newer Entries' ); // display newer posts link ?>
</div>
</nav>
<?php } ?>
//restore original post data
<?php wp_reset_postdata(); ?>
You could easyly alter your code to also display labels for letters without posts
Please use this below code. The following code you should use in your post type template: it's really work for me... I have also tested this code.... See screenshots 1. http://prntscr.com/dxzi22 (full A to Z) 2. http://prntscr.com/dxziih (Full A to Z with Pagination)... you need do to some CSS for that...
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array('paged' => $paged,'posts_per_page' => -1,'post_type' => 'services','post_status' => 'publish','orderby' => 'title','order' => 'asc');
$fruits = new WP_Query($args);
if($fruits->have_posts()){
$current_first_letter = '';
$t = array();
$s = array();
while($fruits->have_posts()){
$fruits->the_post();
$title = get_the_title();
if(is_string($title)){
$first_letter = strtoupper($title[0]);
if($first_letter != $current_first_letter){
$t[] = $first_letter;
$current_first_letter = $first_letter;
}
}
$s[$first_letter][] = get_the_title();
}
}
$t = array_unique($t);
$tc = count($t);
$sc = count($s);
for($i=0; $i<$tc; $i++){
?>
<div>
<h4><?php echo $t[$i]; ?></h4>
<ul>
<?php
foreach($s as $key => $value){
if($key == $t[$i]){
$vc = count($value);
for($j=0; $j<$vc; $j++){
?>
<li><?php echo $value[$j]; ?></li>
<?php
}
}
}
?>
</ul>
</div>
<?php
}
if($fruits->max_num_pages > 1){ ?>
<nav class="prev-next-posts">
<div class="prev-posts-link">
<?php echo get_next_posts_link( 'Older Entries', $fruits->max_num_pages ); ?>
</div>
<div class="next-posts-link">
<?php echo get_previous_posts_link( 'Newer Entries' ); ?>
</div>
</nav>
<?php } ?>
<?php wp_reset_postdata(); ?>
I have created a page template with a nice layout using the lovely custom fields plugin so my client can easily update the content.
I created a loop on that page template that displays the relevant information nicely;
Here is the loop I made:
<?php
$args = array( 'post_type' => 'cripps_staff', 'posts_per_page' => 300 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo '<div class="col-md-3 spacetop">';
echo '<a href="'.get_permalink().'">';
echo get_post_meta($post->ID,'image',true);
echo '</a>';
echo '<h2 class="staffname">';
echo get_post_meta($post->ID,'staff_name',true);
echo '</h2>';
echo '<h2 class="staffrole">';
echo get_post_meta($post->ID,'staff_role',true);
echo '</h2>';
echo '<h2 class="staffnumber">';
echo get_post_meta($post->ID,'staff_telephone_number',true);
echo '</h2>';
echo '<h2 class="staffemail">';
echo get_post_meta($post->ID,'staff_email_address',true);
echo '</h2>';
echo '</div>';
endwhile;
?>
I created taxonomies so the staff members are split into categories.
I am then using a plugin called Taxonomies filter to create those dropdown options you will see. When you select an element in the dropdowns, Wordpress goes to/changes the page to a custom search results page I created. I want my search results to be displayed exactly like my loop on the People's template. Currently it just spits it out the title in a h1 tag.
Here is the code I got from the Twenty Fourteen theme:
<?php
// Start the Loop.
while ( have_posts() ) : the_post();
/*
* Include the post format-specific template for the content. If you want to
* use this in a child theme, then include a file called called content-___.php
* (where ___ is the post format) and that will be used instead.
*/
get_template_part( 'content', get_post_format() );
endwhile;
// Previous/next post navigation.
CrippsTheme_paging_nav();
else :
// If no content, include the "No posts found" template.
get_template_part( 'content', 'none' );
endif;
?>
How can I get the search results to look exactly like my Post loop?
I managed to resolve this completely with the help of Pieter Goosen, who provided me with an awesomely detailed response, see the full answer on Wordpress development forum:
https://wordpress.stackexchange.com/questions/143023/edit-wordpress-loop-taxonomies-filter
Okay, I have the code pulling the custom fields URL and title of the url. Now I can't seem to get it to show the second featured blog. Here is the working code.
<?php $related = get_post_meta($post->ID, "Featured-Blog", $single=true);
$related=explode(',',$related);
$args = array_merge( array('post__in' => $related, $wp_query->query ) );
query_posts($args);
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div id="<?php the_ID(); ?>">
<p class="caption"><?php the_title(); ?></p>
</div>
<?php endwhile; else: ?>
<p>no related</p>
<?php endif; wp_reset_query();?>
This code example here produces two results, which is almost what I want. Which is caused by the foreach I believe. I do not want to use the code below, but I need to find a way to add the foreach I think to get it to list all of the featured-blogs if I have more than one.
<?php
$custom_fields = get_post_custom($post_id); //Current post id
$my_custom_field = $custom_fields['Featured-Blog']; //key name
foreach ( $my_custom_field as $key => $url )
echo $key ="<a href='".$url."'>TEST</a><br /><br /><br/>";
?>
Here is a screenshot showing my Custom Fields if it helps at all, and the results they are showing on the site. screenshot
Example 1: You are using the actual word 'TITLE' for the link use <?php the_title() ?> instead
Example 2: You are not building link at all. Your href attribute is empty. Cut echo $featured_blog1 and paste it to href attribute to end up like so:
Example 3: Same as 2
Also you can delete dose instructions or put them inside <?php ?> code so they are not visible to viewers.
Hope this helps.
If you need more info just ask. ;)
I have this custom post type Gallery. I want to call first image from the posts.
<?php
$item_count = 1;
$args = array( 'post_type' => 'gallery', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
$item_count = 1;
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php the_title(); ?>
<div class="count"><?php echo $item_count; ?></div>
<div class="thumbnail">
// THE FIRST GALLERY ATTACHMENT IMAGE
</div>
<?php $item_count++; ?>
<?php endwhile; ?>
Any ideas?
Note: I added Gallery no simple image on the post!
Check this WordPress Codex example.
The code will show the first image associated with the post.
Or check this WordPress forum discussion that also deals with this problem.
UPDATE:
Go to Appearance > Editor and select Theme functions (functions.php).
at the end of the file add this:
// Get URL of first image in a post
function catch_that_image($my_postid) {
global $post;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', get_post_field('post_content', $my_postid), $matches);
$first_img = $matches [1] [0];
// no image found display default image instead
if(empty($first_img)){
$first_img = "/images/default.jpg";
}
return $first_img;
} ?>
Now in your code you modify this part of the code:
<div class="thumbnail">
<?php echo catch_that_image($loop->ID) ?>
</div>
UPDATE V2
I modified the code to suit your code.
UPDATE V3
I tried the code on my development site and I modified it further until the code worked as it should. You should not have any problems now.
How do I get a random post in Wordpress?
I would like to display a button on a page that, when pressed, goes to a random post from the blog. I don't want a random post to be displayed on the page, I just want a link that leads to that post.
I tried searching for a code on Google and here at stackoverflow but no success.
Thanks...
UPDATE:
Here is my template code:
<?php /*Template Name: Random*/ ?>
<?php get_header(); ?>
<nav><?php wp_nav_menu(array('menu' => 'Main Nav Menu')); ?></nav>
<div id="main-content-archive">
<div class="grey-text">Random post</div>
<?php $query = new WP_Query( array ( 'orderby' => 'rand', 'posts_per_page' => '1' ) );?>
<?php if (have_posts()) : while ( $the_query->have_posts() ) : $the_query->the_post();
echo '<li>';
the_title();
echo '</li>';
?>
<?php endwhile; ?>
<?php else : ?>
<h2>Not Found</h2>
<?php endif; ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
create a page template, and use the following code to get a random post:
//Create WordPress Query with 'orderby' set to 'rand' (Random)
$the_query = new WP_Query( array ( 'orderby' => 'rand', 'posts_per_page' => '1' ) );
// output the random post
while ( $the_query->have_posts() ) : $the_query->the_post();
echo '<li>';
the_title();
echo '</li>';
endwhile;
// Reset Post Data
wp_reset_postdata();
then in a page, just use:
see a random post
I found this post which gave me desired results...
Here's a solution copy/pasted from the wpbeginner blog post. No copyright infringement intended.
Just add the following code to the functions.php file:
add_action('init','random_add_rewrite');
function random_add_rewrite() {
global $wp;
$wp->add_query_var('random');
add_rewrite_rule('random/?$', 'index.php?random=1', 'top');
}
add_action('template_redirect','random_template');
function random_template() {
if (get_query_var('random') == 1) {
$posts = get_posts('post_type=post&orderby=rand&numberposts=1');
foreach($posts as $post) {
$link = get_permalink($post);
}
wp_redirect($link,307);
exit;
}
}
Use mydomain.com/random/ as your href for your button that leads to the random post.
Thanks everyone who contributed for your help...
Cheers!
I find it is more useful to have a URL that will redirect to a random post that you can use as link in sidebar or in menus. If it is a single WP site and even on wp.com it's really easy, for a blog at
http://mygroovywpsite.me/
All you need to do is append it with ?random
http://mygroovywpsite.me/?random
I found this did not work (nor the wp_beginner code above) on subsites in my multisite installation, either approach just loaded the home page. Maybe I had some funky cache issues. The way I do this on many sites is a few more steps w/o plugins.
First make a Page in your site called "Random" / with the slug "random" -- it does not need any content in it
Then create a page-random.php template
<?php
/*
Random Post Picker
Use on page to send viewer to random post optionally mod query
*/
// set arguments for WP_Query on published posts to get 1 at random
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 1,
'orderby' => 'rand'
);
// It's time! Go someplace random
$my_random_post = new WP_Query ( $args );
while ( $my_random_post->have_posts () ) {
$my_random_post->the_post ();
// redirect to the random post
wp_redirect ( get_permalink () );
exit;
}
?>
Then you get the re-direct for any link on your blog ...../random w/o any wrestling with .htaccess
I've done it this way because I've had to modify the query, sometimes for custom post type, sometimes to restrict to category, etc.
I only had one site that was a problem because the hosting suppressed the use of mySQL queries with ORDER BY RAND()
Another Simple solution to display Random Post
1.First a create a custom page template. Name it as random post or a name of your choice!
2.Open the page and remove the default wp loop and Paste the code below
3.To change the no of post change the number ‘1’ to your choice!
<?php
query_posts(array('orderby' => 'rand', 'showposts' => 1));
if (have_posts()) :
while (have_posts()) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php endwhile;
endif; ?>
source: http://www.yengkokpam.com/displays-random-posts-in-a-page/
Check This
<ul>
<?php
$args = array( 'numberposts' => 5, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<li><?php the_title(); ?></li>
<?php endforeach; ?>
</ul>