在WordPress中向前端用户显示错误和信息消息

时间:2014-03-04 17:31:47

标签: php wordpress

我的目标是在WordPress中向前端用户显示错误和信息消息。

在BuddyPress中,bp_core_add_message()可用于向WP cookie添加反馈(错误/成功)消息,以便在页面重新加载后显示。 WordPress中是否有这样的功能?

价: https://github.com/buddypress/BuddyPress/blob/master/bp-core/bp-core-functions.php#L902

更新

改编自bp-core-functions.php:

function add_message( $message, $type = '' ) {

    // success is the default
    if ( empty( $type ) )
        $type = 'success';

    // Send the values to the cookie for page reload display
    @setcookie( 'wp-message',      $message, time() + 60 * 60 * 24, COOKIEPATH );
    @setcookie( 'wp-message-type', $type,    time() + 60 * 60 * 24, COOKIEPATH );

}


function setup_message() {

    if ( isset( $_COOKIE['wp-message'] ) )
        $template_message = stripslashes( $_COOKIE['wp-message'] );

    if ( isset( $_COOKIE['wp-message-type'] ) )
        $template_message_type = stripslashes( $_COOKIE['wp-message-type'] );

    add_action( 'template_notices', 'render_message' );

    if ( isset( $_COOKIE['wp-message'] ) )
        @setcookie( 'wp-message', false, time() - 1000, COOKIEPATH );
    if ( isset( $_COOKIE['wp-message-type'] ) )
        @setcookie( 'wp-message-type', false, time() - 1000, COOKIEPATH );
}
add_action( 'wp', 'setup_message', 5 );


function render_message() {

    if ( isset( $_COOKIE['wp-message'] ) ) {
    $template_message = stripslashes( $_COOKIE['wp-message'] );

    if ( ! empty( $template_message ) ) :
        $type    = ( 'success' == stripslashes( $_COOKIE['wp-message-type'] ) ) ? 'updated' : 'error';
        $content = apply_filters( 'render_message_content', stripslashes( $_COOKIE['wp-message'] ), $type ); ?>

        <div id="message" class="template-message <?php echo $type; ?>">
            <?php echo $content; ?>
        </div>

    <?php
        do_action( 'render_message' );
    endif;
    }
}

0 个答案:

没有答案