Home › Forums › General Issues › CPT with single CPT template. Can I 404 conditionally with ACF true/false field? › Reply To: CPT with single CPT template. Can I 404 conditionally with ACF true/false field?
In the time-honoured tradition I have managed to solve this after writing the question.
For anybody who also needs the answer this is how I excluded certain CPT entries from having their own page and appearing in the Yoast XML Sitemap if they did NOT have the “has_page” conditional field checked:
class CPT_Person
{
public static $CPT_PERSON = 'person';
public function __construct()
{
$this->hook_actions();
$this->hook_filters();
}
private function hook_actions()
{
add_action('template_redirect', array($this, 'people_404'));
}
private function hook_filters()
{
add_filter('wpseo_exclude_from_sitemap_by_post_ids', array($this, 'hide_people_from_yoast_sitemap'));
}
public function people_404_ids()
{
// Returns array of people CPT IDs where 'has page' has not been set to true
$exclude_args = array(
'post_type' => self::$CPT_PERSON,
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'has_page',
'value' => 0,
'compare' => '='
),
array(
'key' => 'has_page',
'compare' => 'NOT EXISTS'
)
),
'fields' => 'ids'
);
$the_query = new WP_Query($exclude_args);
return $the_query->posts;
}
public function hide_people_from_yoast_sitemap()
{ // Exclude some people from Yoast XML Sitemap
$exclude_ids = $this->people_404_ids();
return $exclude_ids;
}
public function people_404()
{
// Exclude some people from having single CPT page
if(is_singular(self::$CPT_PERSON))
{
$exclude_ids = $this->people_404_ids();
if (in_array(get_the_ID(), $exclude_ids))
{
global $wp_query;
$wp_query->set_404();
http_response_code(404);
get_template_part(404);
exit();
}
}
}
}
new CPT_Person();
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.