Получение идентификатора следующей / предыдущей записи с использованием идентификатора текущей записи в Wordpress - PullRequest
5 голосов
/ 13 июня 2011

Я хочу написать пользовательскую функцию next / prev для динамического отображения информации о публикации во всплывающем окне fancybox.Поэтому мне нужно использовать PHP для получения следующего и предыдущего идентификатора поста на основе того, что пост в данный момент показывает.Я знаю, каков текущий идентификатор сообщения, и я могу отправить его в функцию, но я не могу понять, как использовать этот идентификатор для получения смежных идентификаторов.

Редактировать: пока мой код(который не работает)

<?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);


?>

Ответы [ 3 ]

7 голосов
/ 13 июня 2011

get_adjacent_post() использует глобальную $post в качестве своей контрольной точки, поэтому вам нужно заменить это:

$this_post = get_post($post_id);

на:

global $post;
$post = get_post($post_id);

WordPress также предоставляетget_next_post() и get_previous_post(), которые вы можете использовать здесь вместо использования get_adjacent_post() со всеми этими аргументами.Вот конечный продукт:

<?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);

?>

Я не уверен, какие ключи вы хотели бы использовать для идентификаторов и названий предыдущих и следующих сообщений в массиве $dataset, поэтому я оставлюэто как сейчас.

3 голосов
/ 19 октября 2012

Чтобы заставить это работать, мне пришлось изменить $next_post->id; на $next_post->ID;, то есть заглавную ID.

Я использовал его в Wordpress на index.php вот так - я вставил это в начало цикла:

<div class="work-post" id="<?php the_ID(); ?>">

тогда в цикле я использую это: `

        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) : ?>
                <a href="#<?php echo $next_post->ID;?>" class="anchorLink"><div>PREV.</div></a>
            <?php endif; ?>
        <!-- call only if a value exists -->

        <!-- call only if a value exists -->
            <?php if($previous_post) : ?>
                <a href="#<?php echo $previous_post->ID;?>" class="anchorLink"><div>NEXT</div></a>
            <?php endif; ?>
        <!-- call only if a value exists -->`
2 голосов
/ 13 ноября 2015

Это мой код, он работал хорошо.$ 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; 
} 

Тогда вы просто вызываете функцию.Пример:

echo get_previous_post_id( $current_id );
echo get_next_post_id( $current_id );

Удачи!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...