Как отобразить форму комментария с шорткодом, удалив ее из позиции по умолчанию?


Я уже смог отобразить форму комментариев в области содержимого публикации с помощью этого кода, что позволяет мне использовать короткий код [wpsites_comment_form]:

add_shortcode( 'wpsites_comment_form', 'wpsites_comment_form_shortcode' );
function wpsites_comment_form_shortcode() {
    ob_start();
    comment_form();
    $cform = ob_get_contents();
    ob_end_clean();
    return $cform;
} 

Что мне нужно, так это удалить форму комментариев в нижней части сообщения (отображение по умолчанию). Когда я удаляю его через панель администратора в разделе Сообщения - Редактировать - Комментарии - Не разрешать, он также удаляется из того места, где он отображался с помощью функции шорткода. Итак, как я могу сделать так, чтобы он отображался только где находится шорткод?

Author: rodrigo nomada, 2015-02-05

1 answers

Версия #1

Кажется, что для темы Двадцать пятнадцать работает следующее:

/**
 * Display the comment form via shortcode on singular pages
 * Remove the default comment form.
 * Hide the unwanted "Comments are closed" message with CSS.
 *
 * @see http://wordpress.stackexchange.com/a/177289/26350
 */

add_shortcode( 'wpse_comment_form', function( $atts = array(), $content = '' )
{
    if( is_singular() && post_type_supports( get_post_type(), 'comments' ) )
    {
        ob_start();
        comment_form();
        print(  '<style>.no-comments { display: none; }</style>' );
        add_filter( 'comments_open', '__return_false' );
        return ob_get_clean();
    }
    return '';
}, 10, 2 );

Где мы разрешаем шорткоду отображать форму комментариев только для отдельных сообщений, поддерживающих комментарии.

Здесь мы используем CSS, чтобы скрыть нежелательное сообщение Комментарии закрыты .

Версия #2

Вот еще один подход без CSS:

/**
 * Display the comment form via shortcode on singular pages.
 * Remove the default comment form.
 * Hide the unwanted "Comments are closed" message through filters.
 *
 * @see http://wordpress.stackexchange.com/a/177289/26350
 */

add_shortcode( 'wpse_comment_form', function( $atts = array(), $content = '' )
{
    if( is_singular() && post_type_supports( get_post_type(), 'comments' ) )
    {
        ob_start();
        comment_form();
        add_filter( 'comment_form_defaults', 'wpse_comment_form_defaults' );
        return ob_get_clean();
    }           
    return '';
}, 10, 2 );

function wpse_comment_form_defaults( $defaults )
{
    add_filter( 'comments_open', 'wpse_comments_open' );
    remove_filter( current_filter(), __FUNCTION__ );
    return $defaults;
}

function wpse_comments_open( $open )
{
    remove_filter( current_filter(), __FUNCTION__ );
    return false;
}
 3
Author: birgire, 2015-07-16 17:04:09