wordpress pagination get current page number from url - wordpress

I need to extract the value of "page" i.e 5 from this url - http://snypher.local/photos/page/5
What should I do to extract it in Wordpress? I am not able to get it from the $_GET super global.

use get_query_var example $page = get_query_var('paged'); in your case it's 5

its work fine i've tested on my current WP (version 3.5.1)
$current_page = max( 1, get_query_var('paged') );
$total_pages = $wp_query->max_num_pages;
echo 'Page '.$current_page.' of '.$total_pages;
Result = Page 3 of 51

function get_url_var($name)
{
$strURL = $_SERVER['REQUEST_URI'];
$arrVals = explode("/",$strURL);
$found = 0;
foreach ($arrVals as $index => $value)
{
if($value == $name) $found = $index;
}
$place = $found + 1;
return $arrVals[$place];
}
$page = get_url_var('page');
I have used this function to get the value of the variable page from the url.

Found a nice solution and I'd like to share it here for I was looking for exactly the same thing!
http://wordpress.org/support/topic/get-current-page-number-for-paginated-posts
So it's like:
<?php echo '(Page '.$page.' of '.$numpages.')'; ?>

Related

Return Number of published posts in a custom post type

<?php
$counter=1;
$counter_new=0;
$args = array('posts_per_page' =>-1,'orderby' => 'post_date','order' =>'DESC','post_type' => 'interview','post_status' => 'publish',
'suppress_filters' => true );query_posts( $args );while (have_posts($args)) : the_post();
if($counter < 8)
{
$counter++;
}
else
{
$counter_new++;
$counter=1;
}
endwhile;
?>
I saw someone else code to find the number of post, as record increase it is not efficient. What is the right way to do? It looks stupid now.
In case you use WPML wp_count_post() will not show correct count of posts for given language. Use this instead:
$posts = get_posts('post_type=yourcustomposttype&suppress_filters=0&posts_per_page=-1');
$count = count($posts);
echo $count;
Take a look at the wp_count_posts() function.
For your example:
$count_posts = wp_count_posts('interview');
$published_posts = $count_posts->publish;
$published_posts will return the number of published posts in your 'interview' custom post type.
One of the other answers won't work if you have WMPL and translations. The other one will work, but will be very inefficient.
With WPML, try this instead:
function my_count_posts( string $post_type = 'post', string $language_code = '', string $post_status = 'publish' ): int {
global $wpdb;
$default_language_code = apply_filters( 'wpml_default_language', null );
$language_code = $language_code !== '' ? $language_code : $default_language_code;
$translation_param = $default_language_code == $language_code ? "IS NULL" : "= '{$default_language_code}'";
$query = <<<SQL
SELECT COUNT( {$wpdb->prefix}posts.ID )
FROM {$wpdb->prefix}posts
LEFT JOIN {$wpdb->prefix}icl_translations ON {$wpdb->prefix}posts.ID = {$wpdb->prefix}icl_translations.element_id
WHERE {$wpdb->prefix}icl_translations.language_code = '{$language_code}'
AND {$wpdb->prefix}icl_translations.source_language_code $translation_param
AND {$wpdb->prefix}icl_translations.element_type = 'post_{$post_type}'
AND {$wpdb->prefix}posts.post_status = '$post_status'
SQL;
return $wpdb->get_var( $query );
}
You'd use it like this:
// counts published "posts" in the default language
$count = my_count_posts();
// counts posts of `post_type=custom_post_type` in the current language
$count = my_count_posts('custom_post_type', apply_filters( 'wpml_current_language', '' ));

Wordpress next_posts_link Linking to wrong URL

I have next_posts_link setup on the single.php, and it generates the following URL:
http://mywebsite.com/news/article1/page/2
However, this url would be redirected to
http://mywebsite.com/news/article1
Any way to get to the second page?
It seems that it's an issue with Wordpress permalinks. I currently use a custom permalink structure
/%category%/%postname%/
Setting the permalinks as default fixes this issue, but this project needs to have the custom permalinks.
You should be using next_post_link() which is meant to navigate between single posts. next_posts_link naviugate between pages
If you however need to navigate a paged post (using <--nextpage-->), then you should make use of wp_link_pages
EDIT
I have recently did the same exact thing on WPSE. As I explain in that post, the structure you need is not available for any permalink structure outside the default permalink structure.
Just a note before I paste that answer, I have done that for the /%postname%/ permalink structure. Just change all instances of /%postname%/ to the appropriate structure
POST FROM WPSE
As I said, this whole setup you are after is not possible natively with pretty permalinks. Your setup probably works with default permalink structure as both queries (the main query and your custom query) read these permalinks in the same way. When you switch to pretty permalinks, the two queries on the single page interpret the URL differently causing one or the other to fail when you try to paginate your custom query
Single pages was never meant to be paginated in this manner, specially using pretty permalinks. I have gone and played around with a couple of ideas, and the best way to accomplish this is
To write your own pagination functions that can read the page number from the URL
Write your own function that can append the page number to the URL, something like adding /2/ to the URL of single pages.
I must stress, if you are paginating single post with <!--nextpage-->, your post will also paginate together with your custom query. Also, if your permalink structure is not set to /%postname%/, the code will fail and display an error message through wp_die()
THE CODE
Here is the code that will get the next/previous page and also add the pagenumber to the URL.
function get_single_pagination_link( $pagenum = 1 ) {
global $wp_rewrite;
if( is_singular() && $wp_rewrite->permalink_structure == '/%postname%/') {
$pagenum = (int) $pagenum;
$post_id = get_queried_object_id();
$request = get_permalink( $post_id );
if ( $pagenum > 1 ) {
$request = trailingslashit( $request ) . user_trailingslashit( $pagenum );
}
return esc_url( $request );
}else{
wp_die( '<strong>The function get_single_pagination_link() requires that your permalinks are set to /%postname%/</strong>' );
}
}
You can use this function as follow to get the link for any page in the single page when paginating your custom query
get_single_pagination_link( 'pagenumber_of_previous_or_next_page' );
Again, as I said, there is no pagination function that will be able to paginate your custom query or read pagenumbers from the URL, so you have to write your own.
Here is my idea of creating links to the next and previous pages in your custom query. If you look closely, you will see how I have used the previous declared function get_single_pagination_link() to get the links to the next and previous pages
function get_next_single_page_link ( $label = null, $max_page = 0 ) {
global $wp_query;
if ( !$max_page ) {
$max_page = $wp_query->max_num_pages;
}
$paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
if( is_singular() ) {
$next_page = intval($paged) + 1;
if ( null === $label ) {
$label = __( 'Next Page »' );
}
if ( ( $next_page <= $max_page ) ) {
return '' . $label . '';
}
}
}
function get_previous_single_page_link( $label = null ) {
$paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
if( is_singular() ) {
$prev_page = intval($paged) - 1;
if ( null === $label ) {
$label = __( '« Previous Page' );
}
if ( ( $prev_page > 0 ) ) {
return '' . $label . '';
}
}
}
You can now use this two functions in your code to paginate your custom query. Both functions work exactly the same as get_next_posts_link() and get_previous_posts_link() and uses the same exact parameters, so you'll need to keep in mind that you need to pass the $max_page parameter for your custom query
Here is your custom query with these functions.
function get_related_author_posts() {
global $authordata, $post;
$paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
$args = array(
'posts_per_page' => 2,
'paged' => $paged
);
$authors_posts = new WP_Query( $args );
$output = '';
if( $authors_posts->have_posts() ) {
$output = '<ul>';
while( $authors_posts->have_posts() ) {
$authors_posts->the_post();
$output .= '<li>' . get_the_title() . '' . get_the_excerpt() . '</li>';
}
$output .= '</ul>';
$output .= get_previous_single_page_link();
$output .= get_next_single_page_link( null , $authors_posts->max_num_pages );
wp_reset_postdata();
}
return $output;
}
If you want your long post to be shown 2 or 3 pages . You just have to add <!--nextpage--> in your post . The content after it will be shown in the next page . Reference

is there a way to use page id = to load more than 1 page?

Evening,
is there a way to use $page id = to load more than 1 page?
ie:
$page_id = 2;
$page_data = get_page( $page_id );
Or am I coming about this the wrong way?
Thanks all!
If by "load more than one page" you mean display the content from more than one page to a single page of the site, then yes you can do it. Here's a way you could do it.
<?php
$my_postid = 114; // This is page id or post id
$content_post = get_post($my_postid);
$content = $content_post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo $content;
?>
You could repeat this block as many times as you would like, as long as you change the ID number in the first line. Hopefully this is what you are asking for, I wasn't sure I understood the question fully.
get_page() is deprecated, use get_post() instead.
ids are unique, and wouldn't be much use if they weren't! If you have an array of posts you can load them with a foreach
$page_ids = array( 1, 2, 3, 4 );
$pagess = array();
foreach( $page_ids as $page_id ) {
$pages[] = get_post( $page_id );
}
You now have $pages as an array of WP_Post objects.

How to Check Which level category it is for wordpress?

Let me tell you the scenario first say the structure of the categories in wordpress is like this
Level 1: Top
Level 2: -Nextme_1
Level 3: --Nextme_2
--Nextme_3
Level 4: ---Nextme_4
---Nextme_5
Now I require to check what is the level of the category? Say I catch a category of level 3 so I have to use different template and if its level 4. Then I need to use another template?
Anybody can give me some hint?
Thanks
Rahul
If you don't have many categories you can try to edit their slug from admin, and then in your page you get the category slug this way:
if (is_category()) {
$cat = get_query_var('cat');
$category = get_category($cat);
echo 'your slug is '. $category->slug;
}
Now, when you're editing the categories slugs try naming them after their level: cat-lvl-1, cat-lvl-2. Then in your page you extract the number from category slug using some php string function, and then you check that number:
if ($category->slug == 1 ) {
//load the template for the category of level 1
}
if ($category->slug == 2 ) {
//load the template for the category of level 2
}
and so on.
Later edit:
Try this:
function get_level($category, $level = 0)
{
if ($category->category_parent == 0) {
return $level;
} else {
$level++;
$category = get_category($category->category_parent);
get_level($category, $level);
}
}
if (is_category()) {
$cat = get_query_var('cat');
$yourcat = get_category($cat);
echo get_level($yourcat);
}
You can call the get_ancestors() function to get an array containing the parents of the given object. Then you need to count elements in the result.
function get_the_level($id, $type = 'category') {
return count( get_ancestors($id, $type) );
}
if( is_category() ) {
$level = get_the_level( $cat );
}
elseif( is_product_category() ) {
$level = get_the_level( $wp_query->get_queried_object()->term_id, 'product_cat' );
}
Thanks a lot. This is superb with slight a change the code that you have written is fine but its not returning any value.(i,e the $level) although its calculating correct. A minor change i did and its work fine now with a slight editing of you code given below..
`
function get_level($category, $level = 0)
{
if ($category->category_parent == 0) {
return $level;
} else {
$level++;
$category = get_category($category->category_parent);
return get_level($category, $level);
}
}
if (is_category()) {
$cat = get_query_var('cat');
$yourcat = get_category($cat);
echo get_level($yourcat);
}
`
Thanks #zuzuleinen
I visited this page months back. I came back today, arrow up on the above solution then still went digging. Although it is a good solution, Wordpress often offers better or close.
get_category_parents()
This function does as Rahul has typed basically. It also calls itself which seems the most logical approach and that is why Rahul gets a point from me on this. Do not use $link, return a string of categories, explode() them then count or I suppose we could count the number of times the separator has been used and add 1.
function get_category_parents( $id, $link = false, $separator = '/', $nicename = false, $visited = array() ) {
$chain = '';
$parent = get_term( $id, 'category' );
if ( is_wp_error( $parent ) )
return $parent;
if ( $nicename )
$name = $parent->slug;
else
$name = $parent->name;
if ( $parent->parent && ( $parent->parent != $parent->term_id ) && !in_array( $parent->parent, $visited ) ) {
$visited[] = $parent->parent;
$chain .= get_category_parents( $parent->parent, $link, $separator, $nicename, $visited );
}
if ( $link )
$chain .= ''.$name.'' . $separator;
else
$chain .= $name.$separator;
return $chain;
}

Using WP_Query within Plugin

Im currently trying to adjust a Content SlideShow Plugin for Wordpress in order to make it compatible with WPML (Multilingual-Plugin). To achieve this, I simply need to fetch the posts from a specific category, put them into an array and return that array. WP_Query gives me a hard time doing this, as it seems like it's fetching the latest post infinite times in the loop. I'm not experienced in writing Wordpress Plugins, so I would be thankful for any hint you can give me.
This is the code of the plugins class method I'm trying to adjust.
function get_valid_posts(){
$validPosts = array();
$this_post = array();
$id_pot = array();
$my_query = new WP_Query('cat=15&showposts=10');
if($my_query->have_posts()) {
while ($my_query->have_posts()) :
$post = $my_query->post;
if(!in_array($post->ID, $id_pot)){
$this_post['id'] = $post->ID;
$this_post['post_content'] = $post->post_content;
$this_post['post_title'] = $post->post_title;
$this_post['guid'] = $post->guid;
array_push($id_pot, $post->ID);
array_push($validPosts, $this_post);
}
endwhile;
}
return $validPosts;
}
Note that I've added the $id_pot array in order to filter duplicate entries, but this shouldn't be necessary if the query / loop would work.
Thanks in advance!
I've managed to solve the problem:
function get_valid_posts(){
$validPosts = array();
$this_post = array();
$id_pot = array();
$i = 0;
$my_query = new WP_Query('category_name=gallery-post&showposts=10');
if($my_query->have_posts()) {
while($i < $my_query->post_count) :
$post = $my_query->posts;
if(!in_array($post[$i]->ID, $id_pot)){
$this_post['id'] = $post[$i]->ID;
$this_post['post_content'] = $post[$i]->post_content;
$this_post['post_title'] = $post[$i]->post_title;
$this_post['guid'] = $post[$i]->guid;
$id_pot[] = $post[$i]->ID;
array_push($validPosts, $this_post);
}
$post = '';
$i++;
endwhile;
}
return $validPosts;
}
$my_query->post returns the data of a specific post. Instead I had to use $my_query->post*s* to get an array with all the posts fetched as an object.
You are missing a call to the function the_post();:
while ($my_query->have_posts()) :
$my_query->the_post();
$post = $my_query->post;
// ...
endwhile;
See The WordPress Loop

Resources