Inserting dynamic content into a page

I see this subject comes up regularly but have not seen an answer to my specific requirement yet.

I’m trying to use a WordPress page as a template and insert database-sourced content (about 20 or so fields of text, including image file names) based on an ID passed as a URL parameter (and index to my database). e.g. www.example.com/examplepage/?pid=123

Before WordPress, I could do this in PHP easily by executing some code to get a database record and then writing out HTML interspersed with those fields.

I have a plugin in WordPress that allows me to do some PHP code snippets on page, but that’s in the page body and I believe the header has already been written out. The header has fields like title and meta desc that I’d like to be populated by dynamic content.

I’ve seen plug-ins for CMS-like management of real estate listings, movies, etc. but my database handling is a but unusual so I have to take a custom build approach.

I understand that I may need to do some work in the functions.php script for my theme in order to dig into WordPress’ page rendering, but I’d like to be careful not to disturb general pages/posts on my site. It’s just this one special page that will accept a parameters and load the appropriate content.

Some advice on the steps I need to take would be most appreciated.

3 s
3

As you are building a page template, you can insert in the content of that template whatever you want and use any PHP snippet you want. So, you can continue doing it as you was doing in PHP. For example, this could be your page template:

<?php
/*
Template Name: My template
*/
get_header();

?>
<main>

    <?php

    if( isset( $_GET['pid'] ) ) {

        // Populate your dynamic content here

    }

    ?>


</main>
<?php get_footer(); ?>

But you are correct about title and meta tags of the document, they may be already set. Here you need to hook into wp_title filter and wp_head action, using is_page_template function to check if you are in the page template.

For example, suppose that your page tempalte file name is something like page-mytemplate.php and it is located in the root of your theme:

add_filter( 'wp_title', function( $title, $sep ) {

    if( is_page_template( 'page-mytemplate.php' ) ) {

        // Modify the $title here
        $title="my new title";

    }

    return $title;

}, 10, 2 );

add_action( 'wp_head', function() {

    if( is_page_template( 'page-mytemplate.php' ) ) {

        // Echo/print your meta tags here
        echo '<meta name=....>';

    }

} );

The problem

The are a big problem with <meta> tags. WordPress has not a standard way to manage <meta> tags of the docuemnt. If you use any plugin that add <meta> tags, you won’t be able to override them unless the plugin offer a way to do it.

Reference

  • wp_title filter
  • wp_head action
  • is_page_template() function

Leave a Comment