If you are wondering how can you display post or page from other website in wordpress using Bricks Builder, then I will show you some example and code to achieve that.
Example 1: Query WordPress Rest Api
Use this code in dynamic data of Bricks Builder with parameter.
echo:get_wordpress_rest_api_post('title');
echo:get_wordpress_rest_api_post('link');One method to including featured image to json data is to use this function
add_action( 'rest_api_init', 'create_api_posts_meta_field' );
function create_api_posts_meta_field() {
// Register the custom REST field
register_rest_field( 'post', 'featured_image_src', array(
'get_callback' => function ( $post_arr ) {
$image_src_arr = wp_get_attachment_image_src( $post_arr['featured_media'], 'medium' );
return $image_src_arr[0];
},
'update_callback' => null,
'schema' => null,
) );
}Example 2: Query Loop from non wordpress Rest API Json
In example below, I use https://api.sampleapis.com/wines/reds as the data source for query loop. Put this code in functions.php file.
// Define the custom query type
add_filter( 'bricks/setup/control_options', function( $control_options ) {
$control_options['queryTypes']['websitesourcename'] = esc_html__( 'WP Posts', 'my-plugin' );
return $control_options;
} );
// Implement the query logic
add_filter( 'bricks/query/run', function ( $results, $query_obj ) {
if ( $query_obj->object_type !== 'websitesourcename' ) {
return $results;
}
// Fetch data from the API
$api_url = 'https://api.sampleapis.com/wines/reds';
$response = wp_remote_get( $api_url );
// Check if request was successful
if ( is_wp_error( $response ) ) {
return 'Error: Unable to fetch data from the API.';
}
// Parse JSON response
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body, true );
// Check if data was decoded successfully
if ( is_array( $data ) && ! empty( $data ) ) {
// Limit the data to 8 items
$results = array_slice( $data, 0, 8 );
}
return $results;
}, 10, 2 );
// Perform additional customization on loop object
add_filter( 'bricks/query/loop_object', function( $loop_object, $loop_key, $query_obj ) {
if ( $query_obj->object_type !== 'websitesourcename' ) {
return $loop_object;
}
// You can perform any additional customization here if needed
return $loop_object;
}, 10, 3 );
// Support custom loop object property
function get_post_from_others_website( $name ) {
$loop_object = \Bricks\Query::get_loop_object();
if ( ! $loop_object ) return false;
if ( ! is_array( $loop_object ) ) return false;
if ( ! array_key_exists( $name, $loop_object ) ) return false;
return $loop_object[ $name ];
}
//Allow code to executed inside bricks
add_filter( 'bricks/code/echo_function_names', function() {
return
['get_post_from_others_website'];
}
);
Then use dynamic data in Bricks Builder with argument like this
echo:get_post_from_others_website('winery');
