We help IT Professionals succeed at work.

Wordpress Only run code if on a certain page

222 Views
Last Modified: 2017-03-13
I have a wordpress site and some custom code that I only what to run if the post is part of a Series.
So my address http://www.MYSITE.com/series/interesting-facts

I want the custom code to run when I am in "Series".  How do I do that?
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
Custom PHP code?

You probably looking for the is_page() function

if (is_page('interesting-facts')) {
  // Do something awesome here
}

Open in new window

CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
After re-reading the question I don't think this will work.

I am assuming you are using a plugin to manage your series? Which one?

Author

Commented:
I'm not using a plugin.
But the above is not correct, what I mean is:
if (is_page('series')) {
  // Do something awesome here
}

Can I do that?  Using that part of the URL?
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
No - the is_page only works on the name of the page - series would be common to all pages.

How have you implemented your pages in your series?
KimputerIT Manager
CERTIFIED EXPERT

Commented:
Use $_SERVER['REQUEST_URI'], check that the first part is '/series'
Just make sure those pages are based on a template (and have the template contain the PHP code).

Author

Commented:
@Julian:
The template is taxonomy-series.php per the wordpress instructions.  For somereason I can't get it to work by the template name.

@Kimputer:
Use $_SERVER['REQUEST_URI'], check that the first part is '/series' -- How do I write that?
KimputerIT Manager
CERTIFIED EXPERT

Commented:
<?php

if (substr($_SERVER['REQUEST_URI'], 0, 7) == '/series') {

//code here
 
}
?>
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
The $_SERVER approach will most likely work but I am interested to see what the WP way of doing this is.

If you put this code into taxonomy-series.php - what do you get
<?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); 
echo "<pre>" . print_r($term, true) . "</pre>"; ?>

Open in new window

Author

Commented:
AH!  Also, I know this is not recomended but can y'all look at this question?
https://www.experts-exchange.com/questions/29008620/Wordpress-Query.html

Author

Commented:
@julian:
WP_Term Object
(
    [term_id] => 16
    [name] => Serie 1
    [slug] => serie-1
    [term_group] => 0
    [term_taxonomy_id] => 16
    [taxonomy] => series
    [description] =>
    [parent] => 0
    [count] => 1
    [filter] => raw
    [term_order] => 0
)
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION