Function and usage of get_post_galleries() in wordpress


Answers ( 1 )


    The get_post_galleries() function in WordPress is designed to retrieve galleries embedded within the content of a specified post. Here's a detailed explanation of its functionality and usage:


    get_post_galleries( int|WP_Post $post, bool $html = true ): array


    This function extracts gallery information from a post's content. Galleries in WordPress are often inserted using shortcodes. get_post_galleries() parses these shortcodes and retrieves the galleries.


    1. $post (int | WP_Post) - Required. This parameter can be either the post ID or the WP_Post object itself. It specifies the post from which you want to extract galleries.

    2. $html (bool) - Optional. Determines the format of the data in the returned array.

      • If set to true (default), the function returns the HTML content of the galleries.
      • If set to false, it returns the gallery data (such as image sources) without HTML.


    • Array: The function returns an array of arrays. Each inner array contains data related to a specific gallery found in the post. The data includes gallery details and the source URLs of the images, all parsed from the expanded shortcode.

    Sample Usage:

    Scenario 1: Retrieve HTML Content of Galleries

    $post_id = 123; // Replace with your post ID
    $galleries = get_post_galleries( $post_id, true );
    foreach ( $galleries as $gallery ) {
        echo $gallery; // This will print the HTML content of each gallery

    Scenario 2: Retrieve Gallery Data Without HTML

    $post = get_post( 123 ); // Replace with your post ID
    $galleries = get_post_galleries( $post, false );
    foreach ( $galleries as $gallery ) {
        // Process the gallery data (like image srcs)
        print_r( $gallery );

    In these examples, $galleries will contain either the HTML content of the galleries or their data, depending on the $html parameter. You can loop through $galleries to access and process each gallery individually.

Leave an answer