Don’t you just hate it when you have to hard code a post/page Id because you are working in a staging environment and you don’t know if the IDs will match up when you get to go live. Having to go and sort out every theme based link is a nightmare and time consuming. I have written a small method to simply return the ID of a page which contains a specific shortcode.

My example is that I need to pre-fill a Contact Form 7 field from the querystring (I will explain how to do this in another post). I am using a shortcode driven dynamically generated grid for a booking calendar with enquire buttons next to each date. As a quick and simple implementation I want to have the user press a button to enquire and it take them to the booking/enquiry form with their chosen date filled in. So when generating the enquire buttons I am providing a URL and attaching my own bit at the end. To save me hard coding the URL or using something like this:

<?php echo get_permalink(123); ?>

I simply do this:

<?php echo sb_get_url_by_shortcode('[sb_autocomplete_cf7]'); ?>

The function will return the URL of the page that uses that shortcode. In this case the shortcode in question adds some jQuery to the page with contact form 7 on it but you can just as easily look for a specific contact form 7 instance or any other shortcode based page. Consider how WooCommerce works. It adds a few pages each with a shortcode which powers the system so if I wanted to link from my theme or another plugin to the store then this method would be appropriate regardless of the page name or permalink/slug the site owner chooses to use.

The code

function sb_get_url_by_shortcode($shortcode) {
	global $wpdb;

	$url = '';

	$sql = 'SELECT ID
		FROM ' . $wpdb->posts . '
		WHERE
			post_type = "page"
			AND post_status="publish"
			AND post_content LIKE "%' . $shortcode . '%"';

	if ($id = $wpdb->get_var($sql)) {
		$url = get_permalink($id);
	}

	return $url;
}

A donate button!

Be the first to hear about new products/updates!

This is a mailing list for those people interested in being toldĀ when we releaseĀ a new product (Divi plugin or Theme).

We shall also use this list to let you know about product updates and releases.

You have Successfully Subscribed!