First, I recommend against using PHP in post content plugins. Creating your own plugin is simple enough, it’s as easy as creating a php file and adding a plugin header to the top of the file:
<?php
/**
* Plugin Name: Delivery Plugin
*/
Upload the file to the plugins directory, and activate it via the Plugins menu in admin.
From here on, we’ll assume you’ve created a page under Pages menu, with the slug delivery
.
Next step is to add a rewrite rule for the “pretty” URLs, and a query var delivery_location
to hold the value of whatever location was passed in the URL:
function wpd_delivery_rewrite() {
add_rewrite_tag(
'%delivery_location%',
'([^/]+)'
);
add_rewrite_rule(
'^delivery/([^/]+)/?',
'index.php?pagename=delivery&delivery_location=$matches[1]',
'top'
);
}
add_action( 'init', 'wpd_delivery_rewrite' );
After adding this function to your plugin file, go to the Setting > Permalinks page in admin, which will flush rewrite rules and make this rule active.
Now you can visit /delivery/some-location/
and you will see the content of the delivery page.
Next, we’ll add a filter to the_content
so we can dynamically insert some text into the page content when it’s viewed:
function wpd_delivery_content( $content ) {
if( false !== get_query_var( 'delivery_location', false ) ){
$content .= 'Delivery location is ' . get_query_var( 'delivery_location' );
}
return $content;
}
add_filter( 'the_content', 'wpd_delivery_content' );
This checks if delivery_location
was set, and outputs the value if it exists. You can add your code within this function that fetches whatever data you need to output to the page. Note that the function must return
its content for the page to render properly, it can’t directly output via echo
or directly print it.
The last step is to hook the wp_head
action, where we can insert our own meta tags. We do the same check for our custom query var, and output whatever tags we want:
function wpd_meta_tags(){
if( false !== get_query_var( 'delivery_location', false ) ){
echo '<meta name="description" content="' . get_query_var( 'delivery_location' ) . '" />';
}
}
add_action( 'wp_head', 'wpd_meta_tags', 0 );