How do you insert php code in or above the header in the WordPress homepage.

Greetings Experts --

I am looking for a way to insert arbitrary php code in or above the header on the home page and only the home page of a WordPress site.  Alternatively, in true WordPress fashion, the code could exist on every page and just be operative on the home.

My immediate application is to affect a page redirect if the user is on a mobile device.  From what I have read, this has to happen before any text is sent to the browser - hence my "above the header" preference.  Anyway, the theme is plenty responsive under normal circumstances, and it would be a waste of time to create an alternative version of every page.  However, the home page is so image intensive that no amount of responsiveness is going to make it palatable on a mobile.

WordPress 4.3
Theme 'X' v4.0.7, Stack 'Renew'
I also have a rudimentary child theme ('X - Child Theme: Renew') to facilitate blogger home pages and to format the list of bloggers like other lists.

I have done due diligence in seeking out existing solutions and found that I am going to need a bit more hand-holding than the typical person asking this type of question.  For example, there is
Redirect to first page form
I understand the php code, but not how to get it into or above the html header.
Another one is
WordPress Redirect
I can find no file by the name of "page-template" in the WordPress or X hierarchies, although there is a "post-template".  The latter consists entirely of function definitions, and nowhere contains the word "header".

Thank you for your indulgence,
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
a page redirect ... has to happen before any text is sent to the browser
While that is technically true, there is always more than one way to get a good result.  You can (and should) use output buffering, almost without exception.  In most cases it makes your site faster, and it solves the "header must come first" problem.  The output buffer can hold your browser output until the PHP script ends, thus allowing you to write PHP logic out of the order required by traditional HTTP Client/Server protocols.

Going forward, you may want to learn about Twitter Bootstrap.  It helps you build responsive, cross-platform web sites with a "mobile-forward" design approach.  Nobody would start a web site any more with a "desktop-forward" design; we all need mobile to be our central design paradigm.  Bootstrap can help you achieve that.
NonComposMentisAuthor Commented:

Thank you for your reply.  I read your articles, which naturally led to more questions.  As I explained in my original question, I am going to need more than the usual amount of hand-holding.  Neither of your articles appear to take the unique challenges of WordPress development into consideration.  "Understanding Client/Server Protocols" talks about buffering, including the ob_start() function, but not how to insert that into the WordPress php stream.  Also, just where and how would I be inserting the companion function ob_end_flush()?

I believe I erred in submitting this question on a Friday night while y'all were out getting drunk :)  I plan to re-submit it Tuesday morning and put "WordPress" as the ONLY category.

Thanks again,
NonComposMentisAuthor Commented:

This is off-topic, but I also have a question about the whole "stateless" thing.  I was going to post it at the end of the article itself, and still will if you want me too, but thought it might interfere with the flow.  If you answer this, and no one else answers my original question, I will accept it as the answer with an appropriate explanation.

Here it is:

I am struggling with what is the difference - in theory - between a 'truly' stateful interaction and the "server-side databases" that you acknowledge exist.  I know my bank knows the time of my of last interaction because the log-in times out.  It may well be that the time-out happens on the client side TOO, but, again as you acknowledge, this can be circumvented by one with the right skills.  I assume by bank also records my log OFF in the database, should that occur before time-out, so it knows that I am no longer logged in.  What then is the distinction between this and stateful interaction?  Is it that state would be kept in RAM?  If so, I would say this is a distinction without a difference.  But perhaps "state" is something more profound than "are you logged in?"  If so, what is the definition of "state"?
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

NonComposMentisAuthor Commented:
One more thing about buffering:  This being WordPress in general and the X Theme in particular, the pages load very slowly (or with great latency).  Slogging through loading up all the php from all the myriad files, only to find out you are going to redirect to a new page and start the process all over again; well that's going to make it unbearable long.  What I need is something far upstream so that fewer files have to be read before it finds out there's going to be a re-direct.

Ray PaseurCommented:
OK, I'll try to answer these things one at a time... :-)

... just where and how would I be inserting the companion function ob_end_flush()?
I would just leave it out - PHP is smart enough to flush the buffers for you.

...definition of "state"?
For some background, please see How the PHP Session Handler Works in this article:

A "Stateful" condition is one in which the server knows something about the client.  A "Stateless" condition is one in which the server knows nothing about the client.  The PHP session helps the stateless client/server protocol appear to be stateful.  I say "appear" because the server truly does not know anything about the client, except what is presented in the HTTP request variables.  These variables include, inter alia, any HTTP cookies that the server set and that the client returned.  So to sum up, the server sets a session cookie, stores session data, and expects the client to send the session cookie with all subsequent requests.  If the client does not send the session cookie, the server cannot find the session information and the stateful appearance will be lost.  Or if another client sends an identical session cookie, the impostor client will be recognized and the server will make the "stateful" connection to the original session  -- possibly with bizarre consequences.  Please see * The Fine Print in the same article.  

TL;DR - this impostor confusion doesn't happen in the "real world."

... the pages load very slowly
That is a problem with all frameworks that use a lot of HTTP requests.  You get one request for each file (not just PHP but more likely JavaScript and CSS are culprits).  One of the ways we remediate this problem is with Grunt, Gulp and similar automation tools that can be used to combine these files.  Another way is with cache.  Sometimes minification helps.  WordPress is aware of the issue and offers some guidance.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
greetings NonComposMentis, , Despite rays references and your responses, that has for me, put this question in a state of non understanding, as I try to get to what your actual problem might be? ?

I went to your site at  -
and it seems to be a well done web site, AND as I changed the width in my firefox PC desktop view by dragging the browser edge, it looks to me to be correctly "Responsive" and looks good even in the most narrow "thin" view. I also saw your homepage on my tablet "mobil" device, it looked good Except (in a narrow view) - the names for the " intellectual heroes" below their images went OUT OF the correct image placement.

So You say your problem is this -

  "the home page is so image intensive that no amount of responsiveness is going to make it palatable on a mobile."

But I do not see your home page as "image intensive", as far as I can tell you only use 6 images, and all of your images are less than 100 Kbs each, I would say your home page is image economize, and efficient.

You say something about redirecting your page to a "mobil" site, This may be difficult these days to detect if the user in on a mobil in the page request "Before" any javascript can be run to detect the specs of the user environment to get a condition for a "mobil" viewer.
Most wordpress themes are made to be workable in any sort of user condition as to the browser size and device.

Can you tell us more about you viewing your site in your phone and tablet, and the problems you see that you need to correct?
NonComposMentisAuthor Commented:
But I do not see your home page as "image intensive", as far as I can tell you only use 6 images ...

Haha, I guess it's all relative.  Have you seen the rest of our site?  We're philosophers; for us a thousand words is worth a picture!

Greetings Slick812 --

Thanks for the kind words.  It helps to know that a professional thinks I'm on the right track.

This may be difficult these days to detect if the user in on a mobil in the page request "Before" any javascript can be run ...

I had imagined just using HTTP_USER_AGENT, although as you say it does seem to be more complicated than that these days.

Can you tell us more about you viewing your site in your phone and tablet, and the problems you see that you need to correct?

Now that I have a fresh look at it, and in light of your comments, there may not need to be any correction.  You mentioned that the names of our intellectual heroes was out of the the correct image placement.  Well, there's that.  But know that the fact that there are labels there at all was a stop-gap move on my part pending a more complete mobile solution.  Prior to that all I had was a mouseover popup giving short biographical information on each philosopher.  Also when I say "mobile" I basically mean "cell phone" since for now that's the mobile device I have to test on.  On my cell phone the three pictures just scroll up in single file.  I never see this on other sites.  Although it is tough to articulate just why it is "bad", I sense that it is not ideal.

Finally, in reference back to my original question, I said that my "immediate application" was to affect a page redirect.  Projects like this help me learn WordPress, and the skill (of injecting php above the page header) is worth having whether it is used for this application or some other.  However, I also know that you guys are loathe to answer questions in the abstract, so I provided my immediate application.
OK, Your site is readable, on a portrait view in phone, but you can make many sizing and relative placement changes to improve your site appearances, although for a philosophical site, the visitors may be more concerned with ease of readability than looks. My opinions follow, You should have your Intro text (Those who understand. . . . .), centered in that space and in a container that has a "Max Width" set so on desktop views, , the words do NOT stretch all the way across the large screen size, it looks awkward like that . . . and change the font to an accent font for that, or at least make it italic.

The telescopic viewers photo could be smaller, , and needs to RESIZE with width even in larger, medium and smaller screen resolutions, because the text beside the photo is more distinctive than the photo (which is more or less a symbol or icon).
You may could resize the keith-5803-35pct.jpg image of keith which is to large for that placement at the native 846px × 1,161px  size, maybe reduce it by half to 500px height.
You can change the "intellectual heros" face image row, and have each image in a container, that also has the name , and the date of birth and death (or other very short bio). . . And I would use a mech that is in wordpress that places a "Read More" clicker touch place below the name (bio), that when clicked-touched, a hidden element <div> would become visible below the read-more clicker, with as much additional text info that you have in the mouse over (hover) pop-up, the mouse over (hover) is not helpful in mobil at all, but the read-more can be functional in both.

You say - "On my cell phone the three pictures just scroll up in single file", . . .
I would use smaller initial image sizes, as these pictures do not seem be for the site users to get a great deal of visual information from a face, with a little more text for bio underneath and the read-more to show additional words ONLY if the user is interested and touches it.

I have not used any wordpress for some time, but I do know there are a couple of wp plugins that can allow you to place PHP in a page, but it sometimes is not a free lunch, as you can step on PHP code and process and page output that is generated by wordpress.
OH, if you do a "Mobil" only alternate site (pages), you can do javascript to redirect, , , ,
but for the pages that I have seen there, the extra effort may not be worth the result improvement (if any).
NonComposMentisAuthor Commented:
there are a couple of wp plugins that can allow you to place PHP in a page
The ones I have seen allow you to put php code in your page, not above it.
NonComposMentisAuthor Commented:
Please see * The Fine Print in the same article.

If you are referring to the part about not being able to log in as two different people, I long ago found the solution for that.  Just use two different browsers.  As long as one is IE and one is Chrome, for example, I can be logged in as two different people - or as you would say, they use different "cookie jars".  This does nothing to explain what you mean by statelessness, however; it just means that each browser has its own state.

NonComposMentisAuthor Commented:
I am done with this question.  Both Ray and Slick812 have been very helpful but failed to answer the original question.

I promised Ray I would accept an explanation of stateful vs. stateless in lieu of answering the original question as long as no one else actually answered it.  The attempt was made, but the answer in my mind was insufficient.  Ray said, "The PHP session helps the stateless client/server protocol appear to be stateful ...  the server truly does not know anything about the client, except what is presented in the HTTP request variables."[emphasis mine]   If I were to continue this conversation, my follow-up question would be "What other kinds of 'knowing' are there and how are they materially different from HTTP request variables [distinction with a difference]?"  Also how did we get from "The server doesn't have states" to "OK, the server has states but the client doesn't so it's still stateless"?  I'm sure Ray could answer these question and equally sure they would lead to more.

Slick812 also provided me with some very good ideas for my website, but also did not answer the question.

I'm giving them an 'A' even though my question remains unanswered, because they were both very knowledgeable and educated me in many ways.  This is typical of E-E.

Ray PaseurCommented:
I think your question was answered, in that you can use output buffering and then you can put the redirect anywhere you want in the PHP scripts.  This was the first response to the question.

When you're trying to understand something with as much deep background and subtlety as stateful vs stateless protocols, you need more than a little background in computer science.  It's only as recently as Roy Fielding's dissertation that we got sturdy formal definitions of some of these concepts, and computers had been around for decades before that.  There are some helpful pages on the wikipedia, but don't be surprised if it doesn't all sink in at one sitting.  Most of us have to study this stuff in a few semesters of college to make sense of it.

In the case of HTTP, the server has data, but not request-to-request state.  The client has stateful responsibility because it must send the entire request - GET, POST, Cookies, etc., all of the variables are the responsibility of the client.
NonComposMentisAuthor Commented:
My question explicitly stated that I was going to need "hand-holding", a position which I reiterated during the conversation.  What I meant (and said that I meant) was that I needed directions on how to implement the solution in WordPress.  The buffering idea, while it may have many virtues, is begging the question for my purposes.  If I knew HOW to insert ob_start() where it needs to go, then I could use the same technique to insert my HTTP_USER_AGENT code.

I wish E-E allowed editing because I do think I went overboard in trying to "justify" splitting up the credit.  I wanted to do that because both respondents had been so helpful, but to get there I had to argue that Ray didn't completely answer the state/stateless question (note: not the original question).  That was easy to do only because the philosopher in me could keep coming back with questions like, "How is this way of knowing materially different from that way of knowing?"  (I was even prepared to drag out Schrodinger's Cat if the conversation had gone on. :) )  No doubt for a "normal person" his explanation was golden.

So I guess it's up to the moderators.  If they want to assign all the credit to Ray, I wouldn't object.
I don't understand? ?

But as 2 your problem, , I guess you expressly mean 2 redirect the page through PHP Before wordpress can get the control.
When I was doing some wordpress sites, I found much more skilled and experienced WP helpful developers at the Wordpress forums, other that at EE, since they specialize in WP, there are now dozens of WP help forms, just google 4 um,

but I tried 2 tell you that detecting mobil in the first request is not a way to go about this, as you used 2 could get info from headers, and get mobil use, but now there are a million different devices and web browsers, and screen res. Its better 2 get the browser specs in javascript and redirect from there.
NonComposMentisAuthor Commented:
I don't understand? ?
Yes, well, I could keep digging my grave, but I think I hit bedrock :)
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.