When I create a WordPress theme, I like to make things dynamic, clean and easy for the user(s) of the theme. Today I came across an issue where I needed to be able to link back from a single custom post type to the page that is using the template that displays the listing of the custom post type. The page with the template is currently named ‘Portfolio’ and it displays all of the ‘Galleries’, the link will take the visitor back to the ‘Portfolio’ from a ‘Gallery’…exciting!

I could use get_permalink( ID ) to get the permalink by the ID, or get_page_by_path( 'Portfolio' ) to get the page (and then its ID) by its name; but what if the user decides to use a different page or change the page name? Then everything goes caca.

Here’s the gist of what I did.

If you’re still reading, then most of this is self explanatory, so I will explain just the magical parts. meta_key is an aka for a custom field, and _wp_page_template is the custom field name that holds the template that is being used for a page. Now that you know this, meta_value is the value that is stored under the name you’re searching for, and since my template file name is template-galleries.php, that is what I am searching for. Note that you must search for the file name and not just the name you gave to the template.

I then make the query, and since I only queried a single page (hoping that the user hasn’t somehow made two pages that display galleries) I drop the outer array and keep the first object. I then use that to display the permalink in the template.

In my instance, I only need the one page, but if you need more, you just need to change your posts_per_page as you see fit.

Leave a Reply

Your email address will not be published. Required fields are marked *

− two = one