I have simple fuction that adds additional comment form field called “Subject”:
add_action( 'comment_form_logged_in_before', 'additional_fields' );
add_action( 'comment_form_before_fields', 'additional_fields' );
function additional_fields () {
echo '<p class="comment-form-subject">'.
'<label for="subject">' . __( 'Your subject' ) . '</label>'.
'<input id="subject" name="subject" type="text" size="30" tabindex="5" /></p>';
}
It works fine, but just now it adds “Subject” field to every comment form.
I need to add this field only for first level/depth of comments.
My goal is:
When user will reply directly to post, he will get “Subject” field in reply form.
When user will reply to comment, he will not see “Subject” field in reply form.
The Reply links
I assume your Reply links look like this:
<a class="comment-reply-link" href="http://wordpress.stackexchange.com/2013/12/29/hello-world/?replytocom=32#respond"
onclick="return addComment.moveForm('comment-32', '32', 'respond', '1')">Reply</a>
and the Cancel Reply link:
<a rel="nofollow" id="cancel-comment-reply-link"
href="http://wordpress.stackexchange.com/2013/12/29/hello-world/#respond" style="">Cancel reply</a>
The Javascript method addComment.moveForm
is defined in /wp-includes/js/comment-reply.min.js
.
Demo plugin:
To hide the extra Subject field for comments replies, you can try to check for the replytocom
GET parameter for the non-Javascript case and hook into the click event for the Javascript case.
Here is a demo Comment Subject plugin: /wp-content/plugins/comment-subject/comment-subject.php
:
<?php
/**
* Plugin Name: Comment Subject
*/
/**
* Add extra Subject comment field when there is no replytocom in the url
*/
function additional_fields () {
$url_query = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_QUERY );
if( FALSE === stripos( $url_query, 'replytocom' ) )
{
echo '<p class="comment-form-subject">'.
'<label for="subject">' . __( 'Your subject' ) . '</label>'.
'<input id="subject" name="subject" type="text" size="30" tabindex="5" /></p>';
}
}
add_action( 'comment_form_logged_in_before', 'additional_fields' );
add_action( 'comment_form_before_fields', 'additional_fields' );
/**
* Add jQuery and load the custom "script.js"
*/
function custom_scripts()
{
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'my-comment-subject',
plugins_url( 'js/script.js' , __FILE__ ),
array( 'jquery' ),
'1.0.0',
TRUE
);
}
add_action( 'wp_enqueue_scripts', 'custom_scripts' );
where you add the file /wp-content/plugins/comment-subject/js/script.js
containing:
jQuery(document).on( 'click', 'a.comment-reply-link', function( event ) {
jQuery('p.comment-form-subject').hide();
});
jQuery(document).on( 'click', 'a#cancel-comment-reply-link', function( event ) {
jQuery('p.comment-form-subject').show();
});