wp query - Set global $wp_query$post variable for dynamic page generation

admin2025-06-04  2

This is a difficult one to describe, but I'll do my best...

I'm trying to set up pages that can be shown based on a second (meta/ACF) slug, dependent on the language the user is using. Essentially, I need to hook into the loading of the 404 page (as the slug won't correlate to an actual page name) and then spoof the page by the meta value.

I've got it mostly sorted, but just struggling with the final hurdle of setting the page to act like a normal page based on the ID as found when querying the meta field.

At the moment, I'm hooking into the wp action, but this could possibly come sooner, I just wanted to hook into the is_404() function, so it doesn't run on pages if the language is the default.

This is where I'm currently at... it seems to be loading the post and showing the correct title etc, but is showing single.php rather than page.php (for a regular page):

if(is_admin() || !is_404()) return;

if (isset($_SERVER['HTTPS']) &&
    ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
    isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
    $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
    $protocol = 'https://';
} else {
    $protocol = 'http://';
}

$url = $protocol . parse_url($_SERVER['HTTP_HOST'] . $_SERVER["REQUEST_URI"], PHP_URL_PATH);
$slug = basename($url);

$pt = "page";
$p = jb_slug_to_post($slug,$pt);
// can find the post ID by custom slug

if(empty($p)){
    // find the post by the actual slug rather than meta/ACF
    global $wpdb;

    $sql = "SELECT p.ID FROM $wpdb->posts p
            WHERE p.post_name = '{$slug}' AND p.post_type = '{$pt}'
            ORDER BY p.post_parent ASC";

    $results = $wpdb->get_col($sql);

    $match = 0;

    if(!empty($results)){
        foreach($results as $r){
            $construct = jb_construct_permalink($r);
            // URL comparison   
            if($url==$construct){
                $match = $r;
                break;
            }   
        }
    }

} else {
    $match = $p;    
}

if($match){
    global $wp_query;       
    $wp_query = new WP_Query(array('p'=>$match));
    $wp_query->is_{$pt} = 1;

    global $post;
    $post = get_post($match);
    setup_postdata($post);
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749021027a315684.html

最新回复(0)