문제

I'm working on an internal knowledgebase and I want to show the post history on the front end (with something like author, date and difference).

I first landed on wp_get_post_revision() (https://developer.wordpress.org/reference/functions/wp_get_post_revision/) and after more searching I found wp_list_post_revisions() (https://developer.wordpress.org/reference/functions/wp_list_post_revisions/) which looks closer to what I want.

However, while messing with this I'm running into errors while updating posts (Updating failed. The response is not a valid JSON response.) and I don't see anything on the front end when I return the shortcode. I was hoping there was a plugin for this but since I cannot find one I'm creating a quick one. What am I doing wrong and what's the best way to accomplish this?

Here is what I've tried:

function history_shortcode() {
    //global $wpdb;
    //$revisions = $wpdb->get_results("select * from {$wpdb->posts} where post_parent={$post_id} and post_type='revision'");

    $revisions = wp_list_post_revisions(get_the_ID());
    return $revisions;

}
add_shortcode( 'history', 'history_shortcode' );
도움이 되었습니까?

해결책

Your shortcode calls wp_list_post_revisions() which echo the output (revision list), hence you get the "updating error".

To fix the issue, you can use output buffering like so:

ob_start();
wp_list_post_revisions( get_the_ID() );
$revisions = ob_get_clean();

Or you could use wp_get_post_revisions() and build the HTML list manually. Here's an example based on the wp_list_post_revisions():

$output = '';

if ( ! $revisions = wp_get_post_revisions( get_the_ID() ) ) {
    return $output;
}

$rows = '';
foreach ( $revisions as $revision ) {
    if ( ! current_user_can( 'read_post', $revision->ID ) ) {
        continue;
    }

    $rows .= "\t<li>" . wp_post_revision_title_expanded( $revision ) . "</li>\n";
}

$output .= "<ul class='post-revisions hide-if-no-js'>\n";
$output .= $rows;
$output .= '</ul>';

// At the end of your shortcode function, make sure to..
return $output;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 wordpress.stackexchange
scroll top