Cómo modificar el contenido comentario persistentemente sobre la base de $ WP_Query?

wordpress.stackexchange https://wordpress.stackexchange.com/questions/4522

  •  16-10-2019
  •  | 
  •  

Pregunta

Para un plugin, necesito para construir mi propio contenido y el contenido comentario filtro muy temprana posterior. el contenido del post / trabajos cambiantes de texto, es decir, las modificaciones terminan en el navegador del cliente. Pero mi comentario modificaciones de contenido / texto de alguna manera no son persistentes, es decir, el cliente recibe el comentario de texto original.

El punto en el tiempo I "gancho en" se define por la template_redirect gancho. entonces yo haga algo como esto:

global $wp_query;

// Iterate over all posts in this query.
foreach ($wp_query->posts as $post) {
    // Edit post text
    $post->post_content = "foo"; // works: ends up at the client

    // Iterate over all approved comments belonging to this post
    $comments = get_approved_comments($post->ID);
    foreach ($comments as $comment) {
        // Edit comment text
        $comment->comment_content = "bar"; // this one is lost
        } 
    }

Tal como se indica a través de los comentarios de código anteriores, $post->post_content = "foo"; tiene efecto en este contexto, pero $comment->comment_content = "bar"; no.

Para realizar un seguimiento de esto abajo al menos un poco más, apliqué un filtro de depuración en el contenido de la entrada y el contenido comentario:

add_filter('the_content', 'var_dump');
add_filter('comment_text', 'var_dump');

Después de la rutina de modificación del contenido anteriormente, estos filtros de impresión "foo" en caso de contenidos enviados, pero el contenido comentario se imprime sin cambios (el contenido original se imprime).

Por lo tanto, $comment->comment_content = "bar"; parece ser una modificación local, mientras que $post->post_content = "foo"; funciona como se desea:. A nivel mundial

O es la base de datos incluso preguntó dos veces para los comentarios para que mi modificación alguna manera se sobreescribe en algún momento?

He intentado trabajar con $wp_query->comments, también. Sin embargo, esta variable es NULL en el punto en el tiempo que deseo y necesidad de conectar en.

La pregunta final y primaria es:

En mi ciclo anterior, ¿qué tengo que hacer, para modificar el contenido comentario persistentemente?

FYI: Estoy utilizando WordPress 3.0.1

¿Fue útil?

Solución

The function that includes the comments template also (re)loads the comments. This means that whatever you do before that point, if you don't save it to the database it will not be used.

There is no way to prevent this SQL query from happening, but you can override the results by hooking into the comments_array filter. I would save your modifications in an array keyed by the comment ID, so you can do quick lookups and replace contents if needed.

$wpse4522_comments = array();

// Somewhere in your template_redirect (why not wp_head?) hook:
foreach ($wp_query->posts as $post) {
    // Edit post text
    $post->post_content = "foo"; // works: ends up at the client

    // Iterate over all approved comments belonging to this post
    $comments = get_approved_comments($post->ID);
    foreach ($comments as $comment) {
        // Edit comment text
        $GLOBALS['wpse4522_comments'][$comment->comment_ID] = 'bar';
    } 
}

// And this loads the content back into the array from comments_template()
add_filter( 'comments_array', 'wpse4522_set_comments_content' );
function wpse5422_set_comments_content( $comments, $post_id )
{
    global $wpse4522_comments;
    foreach ( $comments as &$comment_data ) {
        if ( array_key_exists( $comment_data->comment_ID, $wpse4522_comments ) ) {
            $comment_data->comment_content = $wpse4522_comments[$comment_data->comment_ID];
        }
    }
    return $comments;
}

Otros consejos

Without knowing much more about what you're tyring to accomplish, there are a few possible solutions.

One is to continue doing what you're currently doing to, but to also add a filter to 'comment_text' to alter the comment output. The downside with this is that you're querying the comments multiple times.

Another option is to start an output buffer on 'template_redirect' and print a placeholder on the 'wp_head' hook to mark a spot in the header. Then use the 'comment_text' and 'the_content' filters to alter the output and check for whatever markers you're looking for. Then, in the output buffer callback, have it replace that marker you put in the header with whatever css you need to add. The only issue with this solution is that the buffer size set on the server may not be enough depending on how much content you have in a single page or how small the buffer is.

Licenciado bajo: CC-BY-SA con atribución
scroll top