Let's say I have a post type called jobs
, and a page called contact
with a form in it. Now I want the contact page to show on every job url ending with /contact
. So job-1/contact
, job2/contact
etc.
I want the same contact-page to display but with access to the current job id.
Is this possible?
Let's say I have a post type called jobs
, and a page called contact
with a form in it. Now I want the contact page to show on every job url ending with /contact
. So job-1/contact
, job2/contact
etc.
I want the same contact-page to display but with access to the current job id.
Is this possible?
Share Improve this question edited Dec 16, 2019 at 23:39 nmr 4,5672 gold badges17 silver badges25 bronze badges asked Dec 16, 2019 at 18:37 CintaCinta 101 1- This may be difficult to achieve, and it's definitely not best practice for SEO, as search engines will see all of these as duplicates. Why do you need to make the contact page look like a child of multiple jobs? Perhaps there is another approach to the underlying reason that could be solved another way. – WebElaine Commented Dec 16, 2019 at 22:12
1 Answer
Reset to default 0Yes, it's possible, but think about what WebElaine wrote in comment.
You'll need a query variable (e.g. jobname
) to store the name of jobs
custom post type.
You also need a rewrite rule that interprets /jobs/{post-slug}/contact
address as a "contact" page
and keep {post-slug}
in query variable jobname
.
add_filter( 'query_vars', 'se354723_query_vars' );
add_action( 'init', 'se354723_rewrite_job_contact' );
function se354723_query_vars( $vars )
{
$vars[] = "jobname";
return $vars;
}
function se354723_rewrite_job_contact()
{
$cpt_slug = 'jobs';
$target_page = 'contact-page-slug';
add_rewrite_rule(
"$cpt_slug/([^/]+)/contact/?$",
'index.php?pagename='. $target_page .'&post_type=page&jobname=$matches[1]',
'top'
);
}
You can check value of the new query variable (jobname
) on the "contact" page
with the get_query_var()
function.
$jobID = 0;
$jobname = get_query_var('jobname', false);
if ( !empty($jobname) )
{
$jobname = sanitize_title_for_query( $jobname );
$arg = [
'post_type' => 'jobs',
'name' => $jobname,
'fields' => 'ids',
'posts_per_page' => 1,
];
$result = get_posts( $arg );
if ( is_array($result) && !empty($result) )
$jobID = (int)$result[0];
}