Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress query_var by domain

I'd like to add a query variable to all queries coming from a certain domain.

For example, mydomain.com and proxydomain.com both show the same WordPress site, but for users visiting via proxydomain.com, I'd like to be able to handle their queries differently.

Additionally, I'd like to apply some different CSS styles for visitors coming through proxydomain.com.

I was thinking I could check for the query_var and apply classes based on the presence of that variable.

like image 713
HWD Avatar asked Apr 14 '15 23:04

HWD


2 Answers

This is the code to add to your functions.php file:

add_filter( 'body_class', 'domain_as_body_class' );
function domain_as_body_class( $classes ) {
    $classes[] = sanitize_title( $_SERVER['SERVER_NAME'] );
    return $classes;
}

It adds the sanitized domain of your site (i.e. mydomain-com or proxydomain-com) as class of the body tag of your pages, so you can target the relative class for custom styles.

Update

For the queries you could add a function again in functions.php like:

function is_proxydomain() {
    return 'proxydomain.com' == $_SERVER['SERVER_NAME'];
}

And then use it when needed on a query:

if( is_proxydomain() ) {
    $args = array(
        // arguments for proxydomain.com
    );
} else {
    $args = array(
        // arguments for mydomain.com
    );
}

$query = new WP_Query( $args );
like image 163
d79 Avatar answered Oct 31 '22 09:10

d79


I like the answer of d79 for the first part.

For the queries, I think it would be better to extend WP_Query class ( i.e. WP_Query_Custom ) and have one copy for each domain. Then you can load the file you need based on the domain in the functions.php file, and so you don't need to change in the future your calls everywhere you use WP_Query_Custom, even if you need to add more domains and different versions of WP_Query_Custom.

//in functions.php
$mydomain = str_replace('.', '_', $_SERVER['SERVER_NAME']);
require_once("path/to/my/classes/$mydomain/WP_Query_Custom.php");

 //In each path/to/my/classes/$mydomain/WP_Query_Custom.php

 class WP_Query_Custom extends WP_Query {

function __construct( $args = array() ) {
    // Force these args
    $args = array_merge( $args, array(
        'post_type' => 'my_custom_post_type',
        'posts_per_page' => -1,  // Turn off paging
        'no_found_rows' => true // Optimize query for no paging
    ) );

    add_filter( 'posts_where', array( $this, 'posts_where' ) );


    parent::__construct( $args );

    // Make sure these filters don't affect any other queries
    remove_filter( 'posts_where', array( $this, 'posts_where' ) );
}



function posts_where( $sql ) {
    global $wpdb;
    return $sql . " AND $wpdb->term_taxonomy.taxonomy = 'my_taxonomy'";
}
}

The example class is copied from extending WP_Query

like image 44
appartisan Avatar answered Oct 31 '22 07:10

appartisan