public
Created — forked from alexkingorg/wp-switch-to-post.php

switch_to_post() stack implementation (similar to switch_to_blog()) for WordPress

  • Download Gist
README.txt
1 2 3 4 5 6 7 8 9 10 11 12
# Switch to Post README
 
## Overview
switch_to_post() stack implementation (similar to switch_to_blog()) for WordPress
 
## Questions
1. Do we want to still switch to post if the get_post fails?
2. Have a (bool) return value based on get_post?
 
## Test Steps
1. Include the `debug.php` and `test-actions.php` file
2. Alter Post IDs in test-actions.php to valid post IDs for your WP install
debug.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<?php
function debug_post_stack() {
global $WP_POST_STACK;
echo '<pre>';
print_r($WP_POST_STACK);
echo '</pre>';
}
 
function debug_post($msg = '') {
global $post;
echo '<h2>'.$msg.'</h2>';
echo '<pre>';
print_r($post->ID.' :: '.$post->post_title);
echo '</pre>';
echo '<hr />';
}
add_action('switch_to_post', 'debug_post');
add_action('restore_post', 'debug_post');
test-actions.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
<?php
require_once 'debug.php';
 
function test_init() {
// First post
debug_post('Original'); //440
 
// Switch to a post
switch_to_post(2); // 2
restore_post();
 
switch_to_post(20);
 
switch_to_post(400);
switch_to_post(461);
restore_post();
restore_post();
 
switch_to_post(5);
restore_post();
 
restore_post();
debug_post('Finally, should be back');
}
add_action('wp', 'test_init');
wp-switch-to-post.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
<?php
 
$WP_POST_STACK = array();
 
function switch_to_post($post_id) {
global $WP_POST_STACK, $post;
// Initialize the stack with very first $post->ID
if (!count($WP_POST_STACK)) {
$WP_POST_STACK[] = $post->ID;
}
// Stick our new post_id onto the end
$WP_POST_STACK[] = $post_id;
$post = get_post($post_id);
setup_postdata($post);
do_action('switch_to_post', $post_id);
}
 
function restore_post() {
global $WP_POST_STACK, $post;
 
// If we don't have anything to knock off, just return
if (!is_array($WP_POST_STACK) || !count($WP_POST_STACK)) {
return;
}
// Remove the current post_id off the stack
$removed_post_id = array_pop($WP_POST_STACK);
// Get last value of the array but leave it on the array
$post_id = end($WP_POST_STACK);
if ($post_id !== false) {
$post = get_post($post_id);
setup_postdata($post);
}
do_action('restore_post', $post_id, $removed_post_id);
}

I don't think we don't need to save $removed_post_id in memory, even temporarily, is needed here. We're not going to do anything with that ID.

It's passed to the action...I lean towards passing more than less to hooks, but if you still think saving the memory I can easily take it out

I see, I'd missed that. Let's leave it in.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.