我正在建立一个带有动态构建页面的网站。对我而言,构建每个页面并将其作为wordpress页面是不切实际的,因为其中将有太多页面,并且都使用相同的PHP代码来生成内容。所以我有一个页面,该页面通过GET请求接受一个额外的变量,并基于该页面提供不同的内容。
URL看起来像这样,其中page_id是动态页面的wordpress参数,而myParam是我的自定义参数,该参数控制将从数据库中提取的内容显示在页面上。
http://my-website.com/?page_id=112&myParam=7
它对页面呈现效果很好,但对注释部分效果不佳。我得到的问题是,发表评论后,wordpress返回“香草” URL http://my-website.com/?page_id=112
并剥离我的参数。结果,我无法将myParam保存为评论元数据,并且在发布评论后,页面显然跳到了其他地方。
有什么方法可以使其遵守参数?我一直在努力使它正常工作,但是我尝试的所有方法都失败了:
query_vars
过滤器wp-comments-post.php?myParam=7
以及更多随机尝试和破解以使其起作用。
感谢您的帮助。如您所见,我的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;
}
希望处理类似问题的人可能会发现它有用:)
欢呼声