发表评论时,Wordpress 删除了我的变量

Wordpress strips my variables when posting a comment

我正在构建一个包含动态构建页面的网站。构建每个页面并将其作为 wordpress 页面对我来说是不切实际的,因为它们太多了,所有页面都具有相同的 PHP 代码来生成内容。所以我有一个页面通过 GET 请求获取一个额外的变量,并基于该变量提供不同的内容。

URL 看起来像这样,其中 page_id 是动态页面的 wordpress 参数,而 myParam 是我的自定义参数,用于控制将从数据库中提取的内容以显示在页面上。

http://my-website.com/?page_id=112&myParam=7

它在页面渲染上效果很好,但在评论部分效果不佳。我遇到的问题是,发表评论后,wordpress returns 到 "vanilla" URL http://my-website.com/?page_id=112 并删除我的参数。结果,我无法将 myParam 保存为评论元数据,并且在发表评论后,页面显然会跳转到其他内容。

有什么办法让它遵守参数吗?我一整天都在尝试让它工作,但我尝试的一切都失败了:

并进行了一些随机尝试和黑客攻击以使其发挥作用。

感谢任何帮助。正如您所见,我的 wordpress 技能不是很好 :) 这可能不是实现我所需的最佳方法,但我找不到任何更聪明的解决方案。

再次感谢!

花了几天时间,但设法找到了答案。我敢肯定有更好的方法可以做到这一点,但它确实有效:)

// Step 1: inject hidden property with spotId to comments form
function wp_output_comment_params() {

    if (( isset( $_REQUEST['spotId'] )) && ( $_REQUEST['spotId'] != '')) {
        ?>
            <input type="hidden" name="spotId" value="<?php echo $_REQUEST['spotId']; ?>">
        <?php
    }     
}
add_action( 'comment_form', 'wp_output_comment_params' );

// Step 2: make sure that we return to the same details page where we posted the comment, so we append argument to the redirect URL
add_filter( 'comment_post_redirect', 'ws_redirect_comments', 10,2 );
function ws_redirect_comments( $location, $commentdata ) {
    if (( isset( $_REQUEST['spotId'] )) && ( $_REQUEST['spotId'] != '')) {
        $location = add_query_arg("spotId", $_REQUEST['spotId'], $location);
    }    
    return $location;
}

这应该会在发表评论后处理着陆页。现在将 spotId 添加到评论元数据并使用它来过滤评论以供显示

// Step 3: inject metadata from the post, so we can filter by it later
add_action( 'comment_post', 'ws_comment_post' );
function ws_comment_post($comment_id , $comment_approved) {
    if (( isset( $_REQUEST['spotId'] )) && ( $_REQUEST['spotId'] != '')) {
        add_comment_meta( $comment_id, 'spotId',  $_REQUEST['spotId'] );
    }
}

// Step 4: filter comments by metadata, so we show only comments for the specified spotId
add_filter( 'comments_template_query_args' , 'ws_filter_comments' , 10, 2 );
function ws_filter_comments( $comment_args ) { 

    if (( isset( $_REQUEST['spotId'] )) && ( $_REQUEST['spotId'] != '')) {
        $comment_args['meta_query'] = [
            [
                'key'     => 'spotId',
                'value'   => $_REQUEST['spotId'],
                'compare' => '='
            ]
        ];        
    }

    return $comment_args;
}

希望处理类似问题的人可能会发现它有用:)

干杯