Display Post Data on a Page

Hi,

I’d like to query a single post of a custom post type using the post ID passed to a page via a URL parameter. Whats the best way to do this with Bricks?

eg

Page - /details/?post_id=123

I’ve tried using a template section and the query loop. As I already have a single template for this post type I don’t want to use that, and the query loop doesn’t seem to allow querying a specific post.

Thanks!

In general, this is obvious.

You have a post type template, for everyone. Excellent.
You want one message/post to be different from all of this type, right? So what’s the problem. Go to this post/message and edit it separately!

@zippa71 Maybe take the time to properly read and understand the issue before spouting this kind of useless feedback?

Hi

Here are the functions and the process for that to work.

We need to add a new query type that reads the url parameter to filter the post from the query results.

These are the steps:

  1. Add these new functions to Bricks
/* Here we add the new query to bricks */
add_filter( 'bricks/setup/control_options', 'query_parameters');
function query_parameters( $control_options ) {
    $control_options['queryTypes']['the_custom_query'] = esc_html__( 'Query for post ID' );
    return $control_options;
};

/* Execute the query when selected in Bricks query */
add_filter( 'bricks/query/run', 'exe_new_query', 10, 2);
function exe_new_query( $results, $query_obj ) {
    if ( $query_obj->object_type === 'the_custom_query' ) {
        $results = run_query();
    }
    return $results;
};


/* Collect wordpress post data */
add_filter( 'bricks/query/loop_object', 'collect_post_data', 10, 3);
function collect_post_data( $loop_object, $loop_key, $query_obj ) {
       if ( $query_obj->object_type === 'the_custom_query' ) {
	   global $post;
       $post = get_post( $loop_object );
       setup_postdata( $post );
       }
       return $loop_object;
};


/* The query run that filters the post id from the url */
function run_query() {
  $postidkey = htmlspecialchars($_GET["post_id"]);
    $args = [ 
        'post_type' => 'any',
        'p' => $postidkey,
                  ];
    $posts_query = new WP_Query( $args );
    return $posts_query->posts;
};
  1. In Bricks create / modify a special page and add a new query loop. In the query loop settings, select the new query type “Query for post ID”

Query_for_post_id

  1. When you want to call this page with a specific post, you have to include the post-id in the url. For example, to get post-id 1234, you have to call the special page with the url

main site address / page / ?post_id=1234

Note: This page will show an error if you call it without the post-id value in the url.

The result:

Query_for_post_id2

Cheers

Patric

2 Likes

That’s really helpful thank you