Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save serhiijko/7f95e455d27f6a8b7754004e66e80dc7 to your computer and use it in GitHub Desktop.
Save serhiijko/7f95e455d27f6a8b7754004e66e80dc7 to your computer and use it in GitHub Desktop.

Revisions

  1. @jenssogaard jenssogaard created this gist Feb 22, 2019.
    42 changes: 42 additions & 0 deletions ACF Gutenberg get block fields
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    <?php
    namespace JensSogaard;

    class BlockHelper
    {
    /**
    * Gets ACF fields for a specific block on a given post
    * @author Jens Soegaard <[email protected]>
    */
    public function getBlockFromPage(string $block_id, int $post_id)
    {
    $post = get_post($post_id);

    if (!$post) return false;

    $blocks = parse_blocks($post->post_content);

    foreach($blocks as $block){
    if ($block['attrs']['id'] !== $block_id) continue;

    acf_setup_postdata($block['attrs']['data'], $block['attrs']['id'], true);
    acf_reset_postdata($block['attrs']['id']);

    return get_fields();
    }

    return false;
    }

    /**
    * Return post id by checking for post instance, second POST param post_id (eg. if ACF ajax preview from Gutenberg), third GET page_id (WP preview)
    * @author Jens Soegaard <[email protected]>
    */
    public function getPostId()
    {
    if (get_the_ID()) return get_the_ID();
    if (isset($_POST['post_id'])) return $_POST['post_id'];
    if (isset($_GET['page_id'])) return $_GET['page_id'];

    return false;
    }
    }