Zubair Mushtaq
Zubair Mushtaq

Reputation: 323

Create a single.php template for custom database table records

Is this possible to make a single.php template for displaying the data of custom database table? Like we have a single.php as a detail page for each post. So, the user will see all the entries on a page template offers.php. When he will click on the offer detail link, a new page will be opened which have all the details about offer.

(Updated)

Upvotes: 1

Views: 754

Answers (2)

popeye
popeye

Reputation: 501

For custom route. Install this plugin called WP Route. Go into your theme folder where you'll find all sorts of static php files like 404.php, header.php, etc. Create package.php there. Open you fav editor with functions.php in the same folder and enter the following content:

function create_routes( $router ) {
$router->add_route('package', array(
'path' => 'mobile-packages/package/xyz-data-package',
'access_callback' => true,
'page_callback' => 'updatefunction'
));

 }
add_action( 'wp_router_generate_routes', 'create_routes' );

function updatefunction() {

load_template(get_template_directory() . '/package.php', true );
exit();
}

Open up 404.php file in the same folder and copy theme settings like get_header() and get_footer() to package.php

Let me know if there's anything missing.

Upvotes: 0

Dipak Kumar Pusti
Dipak Kumar Pusti

Reputation: 1723

  1. Use your custom table, if it is really necessary to use. No issues at all.

  2. Create Custom Post Type and if do not want to show that post type in admin menu then you can keep that hidden.

  3. While saving the post apart from inserting to your table just create new post with the custom post type created earlier. Use wp_inset_post to create Wp post. wp_insert_post

  4. So now a record in Custom Table and a Post in WP Posts table. Create a post_meta named as "custom_linked_id" or whatever you may like and update the Custom Tables Inserted ID to the WP POST.

update_post_meta( $WP_POST_ID, 'custom_linked_id', $CUSTOM_TABLE_INSERT_ID);

  1. Now create single page for your new custom post type. Page name structure is single-{cpt}.php. By default you will get your single post here.

  2. Just inside the loop get the related custom ID by calling the post_meta. So sample code will be like,

$custom_id = get_post_meta( get_the_id(), 'custom_linked_id', true );

  1. Now using that ID you can get all your data from custom table.

Note

Columns used in your custom table can be stored as meta values, it is very easy to achieve and effective.

Hope that helps.

Upvotes: 1

Related Questions