Notes about WordPress Gutenberg themes development.

  • DOING_AJAX, block admin access

    Read more

    To block the access to the admin page to users, but allowing the access to ajax at the same time:

    add_action( 'admin_init', 'dev__block_admin_access', 100 );
    
    function dev__block_admin_access() {
    
        if ( ! defined( 'DOING_AJAX' ) && ! current_user_can( 'edit_pages' ) ) {
            exit( wp_redirect( esc_url( home_url( '/' ) ) ) );
        }
    }

    source: https://developer.wordpress.org/reference/functions/wp_doing_ajax/

  • Using ajax

    Read more

    Server side :

    function fn(){
    
    	header( 'Content-Type: application/json; charset=utf-8' );
    	echo json_encode( 'some response' );
    
    	// don't forget this one below :
    	exit();
    
    }
    
    add_action( 'wp_ajax_actionname', 'fn' );
    add_action( 'wp_ajax_nopriv_actionname', 'fn' );

    Client side :

    const url = siteURL + '/wp-admin/admin-ajax.php?action=actionname';
    
    fetch(url)
    	.then(response => response.json())
    	.then(result => console.log(result));