Getting Next/Previous Post ID using Current Post ID in Wordpress - php

I want to write a custom next/prev function to dynamically display post information in a fancybox pop-up. So I need to use PHP to get the next and previous Post ID based on whatever Post is currently showing. I know what the current post ID is and I can send that to a function ok, but I can't figure out how to use that ID to obtain the adjacent IDs.
Edit:Here is my code so far (which is not working)
<?php
require_once("../../../wp-blog-header.php");
if (isset($_POST['data'])){
$post_id = $_POST['data'];
}else{
$post_id = "";
}
$wp_query->is_single = true;
$this_post = get_post($post_id);
$in_same_cat = false;
$excluded_categories = '';
$previous = false;
$next_post = get_adjacent_post($in_same_cat,$excluded_categories,$previous);
$post_id = $next_post->id;
$title = $next_post->post_title;
$dataset = array ( "postid"=>$post_id, "posttitle"=>$title );
//Because we want to use json, we have to place things in an array and encode it for json.
//This will give us a nice javascript object on the front side.
echo json_encode($dataset);
?>

get_adjacent_post() uses the global $post as its reference point, so you'll want to replace this:
$this_post = get_post($post_id);
with this:
global $post;
$post = get_post($post_id);
WordPress also provides get_next_post() and get_previous_post(), which you can use here instead of using get_adjacent_post() with all of those arguments. Here's the final product:
<?php
require_once("../../../wp-blog-header.php");
if (isset($_POST['data'])){
$post_id = $_POST['data'];
}else{
$post_id = "";
}
$wp_query->is_single = true;
global $post;
$post = get_post($post_id);
$previous_post = get_previous_post();
$next_post = get_next_post();
$post_id = $next_post->id;
$title = $next_post->post_title;
$dataset = array ( "postid"=>$post_id, "posttitle"=>$title );
//Because we want to use json, we have to place things in an array and encode it for json.
//This will give us a nice javascript object on the front side.
echo json_encode($dataset);
?>
I'm not sure what keys you'd like to use for the IDs and titles of the previous and next posts in the $dataset array, so I'll leave that as is for now.

To get this to work I had to change $next_post->id; to $next_post->ID;, i.e. capitalise ID.
I used it in Wordpress on index.php like this – I inserted this at the top of the loop:
<div class="work-post" id="<?php the_ID(); ?>">
then within the loop I use this:
`
if (isset($_POST['data'])){
$post_id = $_POST['data'];
}else{
$post_id = "";
}
$wp_query->is_single = true;
global $post;
$post = get_post($post_id);
$next_post = get_next_post();
$previous_post = get_previous_post();
?>
<!-- call only if a value exists -->
<?php if($next_post) : ?>
<div>PREV.</div>
<?php endif; ?>
<!-- call only if a value exists -->
<!-- call only if a value exists -->
<?php if($previous_post) : ?>
<div>NEXT</div>
<?php endif; ?>
<!-- call only if a value exists -->`

This is my code, it worked good. $post_id is current post ID.
function get_previous_post_id( $post_id ) {
// Get a global post reference since get_adjacent_post() references it
global $post;
// Store the existing post object for later so we don't lose it
$oldGlobal = $post;
// Get the post object for the specified post and place it in the global variable
$post = get_post( $post_id );
// Get the post object for the previous post
$previous_post = get_previous_post();
// Reset our global object
$post = $oldGlobal;
if ( '' == $previous_post )
return 0;
return $previous_post->ID;
}
function get_next_post_id( $post_id ) {
// Get a global post reference since get_adjacent_post() references it
global $post;
// Store the existing post object for later so we don't lose it
$oldGlobal = $post;
// Get the post object for the specified post and place it in the global variable
$post = get_post( $post_id );
// Get the post object for the next post
$next_post = get_next_post();
// Reset our global object
$post = $oldGlobal;
if ( '' == $next_post )
return 0;
return $next_post->ID;
}
Then you just call function. Example:
echo get_previous_post_id( $current_id );
echo get_next_post_id( $current_id );
Good luck!

Related

Using A Global Variable with its Value on another Page (PHP)

I have a wordpress site where Iv assigned a global Variable $rushad and given it the value of a text box found on my product page.
global $rushad;
if((isset($_POST['tmcp_textfield_0'])) && !empty($_POST['tmcp_textfield_1']))
{
$rushad= $_POST['tmcp_textfield_0']; //note i used $_POST since you have a post form **method='post'**
}
I now want to use this information to trigger an email from a plugin Im using.
To do this I modified the plugins code like this....
function woocommerce_gift_coupon_send_action( $post_ids ) {
global $wpdb;
require_once WOOCOMMERCE_GIFT_COUPON_DIR . 'includes/mail-template.php';
$generated_coupon = 0;
foreach ( $post_ids as $post_id ) {
$order = new WC_Order( $post_id );
$items = $order->get_items();
$mailto = $rushad;
$coupons_mail = array();
$sc = false;
$coupons_to_generated = woocommerce_gift_coupon_check_order_coupons_count( $post_id );
$coupons_generated = woocommerce_gift_coupon_check_order_coupons( $post_id );
But its Not working yet.
Any Advice on where Im messing up?
Variable $rushad will not work because it is not defined.
This will work like this
global $rushad;

Get current post id outside the loop. Wordpress

I am making a plugin for wordpress. And the problem is that, how can I get the current post ID outside the loop?
I have a button on the post, and the post ID should be returned when the button is clicked by the user.
So, do anyway to get the post id?
My plugin dir: wp-content\plugins\updateDatabase\js\connectionDatabase.php
Here is my code: And my url http://localhost:8080/wordpress/?p=1169
$post_id = $_GET['p'];
echo $post_id;
$link = getConnection();
$bonusPoint = 0;
$query_sql = "SELECT bonus_point FROM post_data03 WHERE post_id =" .$post_id;
$result = mysqli_query($link, $query_sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$bonusPoint = $row['bonus_point'];
}
} else {
echo "0 results";
}
Using $post:
function getBonusPointFromDataPost()
{
global $wp_query;
global $post;
$post_id = add_action( 'the_post', 'get_post_info' );
$link = getConnection();
}
GetBonusPointFromDataPost() will be fired when the user clicks the button which on the post page. And at the same time, the $post_id should be returned.
And I make a function to return the $post_id, but it only work when I add the action to it.
function get_post_info() {
global $wp_query;
global $post;
$post_id = $wp_query->post->ID;
echo $post_id;
return $post_id;
}
How can I return the $post_id when the user clicks the button.
Here it is,
use global $post to get the current post object
global $post;
echo $post->ID;

Get next_post_link which is Sticky?

I am trying to get the link of next Sticky post with it's title using:
<h2><?php next_post_link('%link') ?></h2>
I have tried passing TRUE argument but that only filters the taxonomy not Sticky Posts.
There is no option in next_post_link to just get sticky post (correct me if i am wrong) . You need custom navigation here. First you need to get all sticky post in array and then make next posts links :
// get all sticky posts
$sticky = get_option('sticky_posts');
// if there are any
if (!empty($sticky)) {
// newest IDs first, optional
rsort($sticky);
$args = array(
'post__in' => $sticky
);
$postlist = get_posts();
$posts = array();
$query = new WP_Query($args);
while ($query->have_posts()) {
$query->the_post();
$posts[] = get_the_ID();
}
//wp_reset_postdata(); uncomment this, if this is a nested loop
$current = array_search($post->ID, $posts);
$prevID = $posts[$current-1];
$nextID = $posts[$current+1];
// Link for previous post
if (!empty($prevID)) {
echo '<div>Prev</div>';
}
// Link for next post
if (!empty($nextID)) {
echo '<div>Next</div>';
}
}

WordPress custom field outside of loop

I currently have a banner image on a site which is pulled in via the featured image. The code below that does this works:
if ( has_post_thumbnail() ) {
$thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );
$url = $thumb['0'];
I would like to change this to use a custom field instead via Advanced Custom Fields. I have made a custom field called banner_image with the type as image url. I cannot seem to get this working however. I have tried the following methods:
Method 1
$image = get_field('banner_image', $post->ID);
$url = $image['url'];
Method 2
$url = get_field('banner_image', $post->ID);
Method 3
$url = get_field('banner_image');
Full PHP Code:
<?php
// Must be inside a loop.
// This is the bit i cannot get working
if(is_post(991)){
global $wp_query;
$postid = $wp_query->post->ID;
$url = get_post_meta($postid, 'banner_image1', true);
//End the bit that doesn't work
} elseif ( has_post_thumbnail() ) {
$thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );
$url = $thumb['0'];
}
else {
$bg = array(
'http://domain.co.uk/wp-content/uploads/2014/07/image.jpg',
'http://domain.co.uk/wp-content/uploads/2014/07/image1.jpg',
'http://domain.co.uk/wp-content/uploads/2014/07/image2.jpg',
'http://domain.co.uk/wp-content/uploads/2014/07/image3.jpg',
'http://domain.co.uk/wp-content/uploads/2014/07/image4.jpg'
); // array of filenames
$i = rand(0, count($bg)-1); // generate random number size of the array
$url = "$bg[$i]"; // set variable equal to which random filename was chosen
}
?>
Does anyone have a method for doing this, I am just getting a blank page on that particular post. Other posts work fine so it isn't breaking the code after elseif?
If you are inside the loop, this works:
$image = get_field('banner_image');
<?php echo $image['url']; ?>
try this one
<?php
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'customField', true);
?>
https://echohelp.wordpress.com/2014/04/28/custom-field-outside-the-loop/
You can use
get_field('banner_image', get_the_ID() );
or
get_field('banner_image', get_queried_object_id() );

Scope: Using Variable Defined in a Function

I have a function in a functions.php file that defines certain variables:
add_action( 'the_post', 'paginate_slide' );
function paginate_slide( $post ) {
global $pages, $multipage, $numpages;
if( is_single() && get_post_type() == 'post' ) {
$multipage = 1;
$id = get_the_ID();
$custom = array();
$pages = array();
$i = 1;
foreach( get_post_custom_keys() as $key )
if ( false !== strpos( $key, 'slide' ) )
$custom[$key] = get_post_meta( $id, $key, true);
while( isset( $custom["slide{$i}-title"] ) ) {
$page = '';
$tzTitle = $custom["slide{$i}-title"];
$tzImage = $custom["slide{$i}-image"];
$tzDesc = $custom["slide{$i}-desc"];
$tzEmbed = $custom["slide{$i}-embed"];
$page = "<h2>{$tzTitle}</h2><img src='{$tzImage}' />";
$pages[] = $page;
$i++;
}
$numpages = count( $pages );
}
}
I'd like to output some of these variables in a template.php file like so: <?php echo $tzDesc; ?> but I can't seem to get it to work. From what I understand about the variables scope, in order to call these variables in another place I need to define them within the global scope and call them as global in this function like I did the $pages, $multipage, $numpages;. That should allow me to plug those variables in where I need them. The problem is when I take them out of the function and define them above within the global scope the entire function stops working.
How do I need to structure this so I can call <?php echo $tzDesc; ?> anywhere in the site and have it echo the defined info?
I don't know if this matters but this is on a WordPress site.
If you want to use <?php echo $tzDesc; ?> anyway, you would need to define $tzDesc as a global variable. However, I don't recommend doing so as global variables are considered poor programming practice.
A better solution would be to have the paginate_slide() add $tzDesc (and other values) to the $post object. That way you have access to these variables anytime you call the_post(). If you go this route, be sure to namespace you variables:
$post->ns_tzDesc = $tzDesc;

Categories