Integrating WordPress into PHP website - php

I apologize in advance if I am not describing the scenario the best way possible, but I will do my best.
I have a e-commerce(ish) website. We are looking to integrate a blog into the existing PHP (MVC) framework.
I am using
define('WP_USE_THEMES', FALSE);
require('/wpengine/wp-blog-header.php');
I have WordPress installed under a subfoler called 'wpengine', but would like to call a WP function to render the theme from a custom controller, so I can place the rendered content into a page as I need it.
Is there a WordPress function to which I can pass GET parameters to render content as wordpress would normally do?
Maybe this will help describe what I am looking to do
->Page Request
---> Loads custom framework
---> Builds custom view
---> Gets content from WP via function call ( rendered category, post, or page )
---> Injects content from WP into view
-> Returns page

Using the following setup for assumptions:
An MVC controller in / that catches everything except /blog
WP serving /blog
WP files in /wp
In the wp/wp-config.php file, add:
define('WP_HOME', 'http://example.com/blog'); # important! no trailing slash
define('WP_SITEURL', 'http://example.com/wp'); # important! no trailing slash
These are the two constants that make a lot of magic happen when making WP work outside of its folder. And things would work more or less out of the box with the above, provided you've a custom-built theme, except for the fact that you want to wrap the WP output in a view.
Some pseudo-code to get you to where you want to… (pick your poison)...
The first approach is to remote fetch WP:
function http_fetch_the_wp_mess() {
$request = remote_fetch('http://path/to/wp/wherever');
extract_and_process_headers($request);
return extract_and_process_content($request);
}
The benefit of first approach is that it's reasonably clean and without risks. You fetch /wp/wherever using http, and str_replace() URIs as needed in the content returned to you. (You could also do this using ajax or even an iframe.) WP gets to live in its own ghetto using a theme with no header, footer or sidebar, and you should be good to go.
The other approach is to include WP, and it's much trickier (as always, the devil is in the details):
function php_include_the_wp_mess() {
# Optionally:
# make_deep_copy_of_superglobals();
ob_start();
require '/path/to/wp/index.php';
# The meat of our procedure:
pray_that_nothing_gets_screwed_up_due_to_using_so_much_global_state();
# Optionally:
# cleanup_superglobals();
# cleanup_and_fix_headers();
return ob_end_clear_up_to_where_started_further_up();
}
Several points in the above:
$_GET, $_POST, $_COOKIE and $_REQUEST all get slashed, as well as — wait for it! — $_SERVER. They occasionally get changed, too. So be on the lookout if you rely on them anywhere further in your request handling. Make backups of any piece of information you might care about before handling it to WP.
Due to your MVC wanting unslashed data, as opposed to WP's slashed data, and due to the fact that both you might register a shutdown actions in addition to those registered by WP, your mileage may vary if they involve any database queries. Be very wary of security considerations if you decide to backup and restore superglobals in the state they were in before WP got fired, because WP and plugins actually can and do issue queries on that shutdown hook.
Needless to say, you still need a custom theme. One with no header, footer or sidebar. Yada, yada.
In case it matters, some plugins break when they can't access their favorite globals; many do, in fact. Some plugins also start output buffers; not as many, but you'll still need to be wary of that when you terminate output buffers.
WP and a rather small number of plugins (mostly, but not only, cache- and anti-spam related) may change some headers, and occasionally do so incorrectly or not as optimally as they should. So be on the lookout on that front if the options they take conflict with your own caching options. Especially when it comes to cookies.
Speaking of caching, you will necessarily need to roll your own: output has already started — even if it's in a buffer — by the time WP kicks in, and the plugins will all cache on the shutdown hook.
If you need to make WP serve arbitrary pages, make WP_HOME point to the site's root folder instead, and it should work…
I'll conclude with two links for further inspiration in the event I did a poor job at discouraging you to try:
https://github.com/kayue/WordpressBundle
https://github.com/fullsixspain/FullSIXWordPressBundle

Related

Get wordpress formatted post content without including wordpress functions

I'm creating a script that gets the content and meta of wordpress posts for an app, doing queries directly on the database because it's way faster than including the wp functions. However the problem is that the post content is saved into the db without formatting. I know that I can get it using
apply_filters('the_content', $content)
but as I said, I would like to avoid wp functions because they are really slow.
Is there any way to "simulate" apply_filters manually?
Is there a better(faster) way to include a wp function other than
require('../wp-load.php');
which seems to be very slow?
The “cheap” method would be including the file wp-includes/formatting.php (and maybe others) and running your code through the desired filter functions, such as wpautop().
However, this does not guarantee that the content is formatted like your WordPress blog – especially because it won't apply the modifications made by plugins. Also, if new WordPress versions introduce new or different filters, your code will not work with them without modifications.
I would indeed recommend including wp-load.php and working with the WP filter API.
I don't think it's overly “slow” (however you may define it), but if performance is an issue, I would recommend reconsidering your architecture.
For example, if you want a website to display contents from your WordPress database, don't pull and render the contents on each page request. Instead, use a caching solution – either one of those that already exist for WordPress, or one on the server level (e.g. Varnish), or you can even implement your own cache, by storing pre-rendered pages and delivering them (semi-)statically.

Wordpress js/css en-queuing after wp_head() - leave inline/in footer, or worth modifying buffer?

I'm writing a plugin for Wordpress developers that allows a dev to include my own widgets in their theme at any point.
The issue is that I can't control when they're going to require/use the widget code - which itself might necessitate the inclusion of external js/css files.
I think it's likely that people will call these widgets often after wp_head() has executed, which means that any js/css inclusions that go with the particular widget they've called will get added inline (or, into the footer if i write it that way).
I can't predict beforehand which widgets they might use to make sure the assets are included at an earlier juncture - and as far as i know, i can't ensure they end up in the [head] short of altering the output buffer with a preg_replace afterwards.
So my question is really two-fold: If you were using the plugin, would you have a problem with potential assets for widgets (like carousels, etc) being loaded inline or in the footer? (I know non-critical js is often loaded in the footer, but have not seen a convention for doing this with css) And if so, is it worth altering the buffer with a preg_replace in order to fix this issue and ensure the externals end up in the [head]? Or perhaps a 3rd option I haven't thought of?
The widgets themselves can be custom-made so i can't guarantee that any scripts that go with them aren't important enough to need to be loaded first (though it's unlikely) and i'm slightly concerned that altering the buffer after every page load would be inefficient.
Thanks!
I would make a requirement that your pluggins must be loaded in the template or in the pluggins before wp_head gets called. It is increasingly important to provide well structured code these days so offering a hack through or a way to produce bad code is IMO bad practice.
Your idea about the replace is nice, it's not a bad thing at all that could allow late-binding of external scripts, but my suggestion stands. If wordpress requires you to setup your CSS and Plugins and Scripts before the wp-head, why not require it too for your framework...
Enforcing good standards should never make you lose interest, at least, the real pro community will like it, while the copy/pasters that don't really understand programming will probably find it frustrating and complex.
Cheers

What to keep in mind when making Wordpress themes

I have been making Wordpress themes for a year or two and keep running into things I need to keep in mind when trying to make my themes as compatible and flexible as possible with their settings, plugins, etc.
Is there a resource that keeps a checklist of all the "don't forgets" of Wordpress theming? What things do you try to keep in mind when building your Wordpress themes?
Examples:
Checking if the author/admin has disabled comments for a particular post.
Remembering to call wp_head() at the end of the <head> tag.
Remembering to call wp_footer() at the end of the <body> tag.
Using bloginfo() variables instead of setting static values for charset, html type, description, etc. so admins can modify such things in the site settings.
Using function_exists() before calling a function from a plugin so it fails gracefully if that plugin isn't installed.
Wordpress documentation has an interesting topic addressing exactly what you're asking: it's called Designing Themes For Public Release. There's also Theme Development General Guidelines. The Templates article is wonderful too.
I don't know other official resources, but it would be interesting to add more info into those three guides. I'm interested in some other answers we may have in your question to complement them.
I'm so used to Wordpress that the examples you wrote just flows automatically when I'm developing, since using a function that outputs domain information such asbloginfo() instead of static values is a good practice in any web development.
A theme development checklist depends more on the intended audience for your theme. If it's beyond the basic blog and moving towards WordPress-as-CMS territory, you'd want to look into:
custom widgets and dynamic sidebars to make features more portable and flexible
support for custom fields, or plugins like MagicFields that implement the former in a whole new way
routing and creating custom templates for different levels of the site (ex: sub-categories get handled by category-x.php)
using a css framework so whoever gets to modify the styles has a higher chance of understanding it better; make sure to include ie support
custom wp-admin section with its own menus, pages, etc.; this is especially necessary if your theme has custom functionality that can be further customized by the user
use the wp_scripts and wp_styles classes and functions to add styles and scripts; this is especially important for javascript, as it prevents duplicate includes and works with dependency scripts (loads jQuery before your jQ script)
make sure the design of the theme doesn't look boring like everything else out there for WordPress
write a theme class; unless you're planning to support PHP4, use PHP5 classes and objects to make your life easier, in terms of feature inheritance and no naming conflicts. look at CodeIgniter and their singleton pattern; it makes custom globals inside template files a lot easier to manage
if you are (and you should be) making your theme a lot more advanced and more like a plugin, then know how to use the WP_Cache and WP_Rewrite objects so your custom queries with $wpdb (yes, you'll need to do these once in a while to get certain custom functionality) are less expensive, and your new pages (if you're rewriting urls) route correctly and your links are correctly dynamically generated, respectively.
last and most importantly, try your hardest to separate presentation (html) from logic (php); this gets hard as you start running custom WP loops and a good solution is the aforementioned theme class.
Our firm also develops a lot of various WordPress & WordPress MU themes & we haven't found any "Official" resources, but one thing we've done is create a basic set of template files can can be used as a "standard" setup in order to speed up our development process.
Then, whenever a new theme needs to be developed, we basically copy / paste this default set of template files into a new theme folder on the WordPress install. For us, items we've included in this default setup are pre-populated header.php, footer.php, index.php, home.php, single.php, functions.php, comments.php, /images (dir), /functions (dir), style.css, /css (dir), /scripts (dir), and a handfull of other items.
Then we've also used Yahoo Grids or Google Blueprint css frames works to also speed up the css work. There's a few other items / files I'm leaving out, but should give you a general idea of what works best for us in our shop.

How Drupal works? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
Could someone provide a architectural overview of the Drupal 7 control flow? Perhaps in the sense of a flowchart about how a page gets generated. What additional resources would you suggest consulting with regards to how Drupal works?
Drupal can be confusing on this front, partially because it has a relatively deep function stack. Although it's procedural PHP it's purely event/listener driven in its architecture, and there's no simple "flow" in the main PHP script for you to look though. I recently did a presentation on this very subject, and the slides are posted on slideshare, but a quick high-level summary may be useful.
Drupal's index.php file functions as a frontside controller. All page are piped through it, and the "actual" url/path the user requested is passed to index.php as a parameter.
Drupal's path router system (MenuAPI) is used to match the requested path to a given plugin module. That plugin module is responsible for building the "primary content" of the page.
Once the primary page content is built, index.php calls theme('page', $content), which hands off the content to Drupal's theming/skinning system. There, it's wrapped in sidebars/headers/widgets/etc..
The rendered page is then handed back to apache and it gets sent back to the user's browser.
During that entire process, Drupal and third-party plugin modules are firing off events, and listening for them to respond. Drupal calls this the 'hook' system, and it's implemented using function naming conventions. The 'blog' module, for example, can intercept 'user' related by implementing a function named blog_user(). In Drupal parlance, that's called hook_user().
It's a bit clunky, but due to a PHP quirk (it keeps an internal hashtable of all loaded functions), it allows Drupal to quickly check for listeners just by iterating over a list of installed plugins. For each plugin it can call function_exists() on the appropriately named pattern, and call the function if it exists. ("I'm firing the 'login' event. Does 'mymodule_login' function exist? I'll call it. Does 'yourmodule_login' exist? No? How about 'nextmodule_login'?" etc.) Again, a touch clunky but it works pretty well.
Everything that happens in Drupal happens because of one of those events being fired. The MenuAPI only knows about what urls/paths are handled by different plugin modules because it fires the 'menu' event (hook_menu) and gathers up all the metadata plugin modules respond with. ("I'll take care of the url 'news/recent', and here's the function to call when that page needs to be built...") Content only gets saved because Drupal's FormAPI is responsible for building a page, and fires the 'a form was submitted' event for a module to respond to. Hourly maintenance happens because hook_cron() is triggered, and any module with mymodulename_cron() as a function name will have its function called.
Everything else is ultimately just details -- important details, but variations on that theme. index.php is the controller, the menu system determins what the "current page" is, and lots of events get fired in the process of building that page. Plugin modules can hook into those events and change the workflow/supply additional information/etc. That's also part of the reason so many Drupal resources focus on making modules. Without modules, Drupal doesn't actually DO anything other than say, 'Someone asked for a page! Does it exist? No? OK, I'll serve up a 404.'
To understand how Drupal works, you need to understand Drupal's page serving mechanism.
In short, all the calls/urls/requests are served by index.php which loads Drupal by including various include files/modules and then calling the appropriate function, defined in module, to serve the request/url.
Here is the extract from the book, Pro Drupal Development, which explains the Drupal's bootstrap process,
The Bootstrap Process
Drupal bootstraps itself on every request by going through a series of bootstrap phases. These phases are defined in bootstrap.inc and proceed as described in the following sections.
Initialize Configuration
This phase populates Drupal’s internal configuration array and establishes the base URL
($base_url) of the site. The settings.php file is parsed via include_once(), and any variable or string overrides established there are applied. See the “Variable Overrides” and “String Overrides” sections of the file sites/all/default/default.settings.php for details.
Early Page Cache
In situations requiring a high level of scalability, a caching system may need to be
invoked before a database connection is even attempted. The early page cache phase lets
you include (with include()) a PHP file containing a function called page_cache_
fastpath(), which takes over and returns content to the browser. The early page cache
is enabled by setting the page_cache_fastpath variable to TRUE, and the file to be included
is defined by setting the cache_inc variable to the file’s path. See the chapter on caching
for an example.
Initialize Database
During the database phase, the type of database is determined, and an initial connection is
made that will be used for database queries.
Hostname/IP-Based Access Control
Drupal allows the banning of hosts on a per-hostname/IP address basis. In the access control
phase, a quick check is made to see if the request is coming from a banned host; if so,
access is denied.
Initialize Session Handling
Drupal takes advantage of PHP’s built-in session handling but overrides some of the handlers
with its own to implement database-backed session handling. Sessions are initialized
or reestablished in the session phase. The global $user object representing the current user
is also initialized here, though for efficiency not all properties are available (they are added by an explicit call to the user_load() function when needed).
Late Page Cache
In the late page cache phase, Drupal loads enough supporting code to determine whether or
not to serve a page from the page cache. This includes merging settings from the database into the array that was created during the initialize configuration phase and loading or parsing module code. If the session indicates that the request was issued by an anonymous user and page caching is enabled, the page is returned from the cache and execution stops.
Language Determination
At the language determination phase, Drupal’s multilingual support is initialized and a decision is made as to which language will be used to serve the current page based on site and user settings. Drupal supports several alternatives for determining language support, such as path prefix and domain-level language negotiation.
Path
At the path phase, code that handles paths and path aliasing is loaded. This phase enables
human-readable URLs to be resolved and handles internal Drupal path caching and
lookups.
Full
This phase completes the bootstrap process by loading a library of common functions, theme
support, and support for callback mapping, file handling, Unicode, PHP image toolkits, form
creation and processing, mail handling, automatically sortable tables, and result set paging. Drupal’s custom error handler is set, and all enabled modules are loaded. Finally, Drupal fires the init hook, so that modules have an opportunity to be notified before official processing of the request begins.
Once Drupal has completed bootstrapping, all components of the framework are available.
It is time to take the browser’s request and hand it off to the PHP function that will
handle it. The mapping between URLs and functions that handle them is accomplished using
a callback registry that takes care of both URL mapping and access control. Modules register
their callbacks using the menu hook (for more details, see Chapter 4).
When Drupal has determined that there exists a callback to which the URL of the browser
request successfully maps and that the user has permission to access that callback, control is handed to the callback function.
Processing a Request
The callback function does whatever work is required to process and accumulate data needed to fulfill the request. For example, if a request for content such as http://example.com/
q=node/3 is received, the URL is mapped to the function node_page_view() in node.module.
Further processing will retrieve the data for that node from the database and put it into a data structure. Then, it’s time for theming.
Theming the Data
Theming involves transforming the data that has been retrieved, manipulated, or created
into HTML (or XML or other output format). Drupal will use the theme the administrator
has selected to give the web page the correct look and feel. The resulting output is then sent to the web browser (or other HTTP client).
Eaton's answer provides a good overview. (I'm new here so I can't mod him up, thus the comment.)
The brutal "aha" moment for me was realizing everything happens through index.php, and then through the waterfall of modules (core first, then by site). To extend core functionality don't rewrite it. Instead copy the module into /sites/all/modules/ or /sites/[yoursite]/modules and extend THAT, or create a new module in those places. Same for themes. Module directories can contain display code as well, in the form of tpl, css etc.
If you're used to stricter MVC type frameworks like Rails, Django etc. all this gets a little confusing. Modules can mix in a lot of display code, and if you're looking at someone else's modules or templates you'll eventually wind up walking backwards through the stack. That's the beauty/pain of working in PHP.
Ironically, "just build an app" might be the worst way to learn this. Drupal does so much out of the box that's simply obscure until you figure out the control flow. There's nothing in a tpl file that tells you where a function with a fun name like l() comes from, for example.
It depends on how deep an understanding you're looking for; if you have a good knowledge of php, I would suggest reading through the code itself, starting with index.php, and then going on to the includes/bootstrap.inc, and then some of the other scripts in that directory.
The key include files:
menu.inc is very important to understanding how the overall system works, as it handles a lot of the implicit mapping of URLs to content.
common.inc has most of the otherwise-mysterious functions that form the basis of the API.
module.inc handles the hook invocations that Eaton mentioned
form.inc deals with form display, submission and processing
theme.inc handles presentation.
There's also some key functionality in the modules/ directory; in particular, modules/node/node.module forms the basis of the node system, which is in general what's used to encapsulate site content.
The code is, in general, very well-commented and clear. The use of Doxygen markup within the commenting means that the code effectively is the canonical documentation.
It also helps to do this using an editor that can quickly jump to the definition of a function. Using vim in combination with ctags works for me; you do have to tell ctags to index .inc, .module, etc. files as php files.
This (for Drupal 6) & this (for Drupal 7) is a pretty good architectural overview of drupal. If you want more detail then I would start writing something most of the documentation is good. Trying to learn it at a high level of detail without something concrete to achieve will be much more difficult that trying something out.
I learned loads by importing the drupal .php code into a NetBeans project.
You can then run the netbeans debugger and watch the different phases of the page come together.
The best books on the subject are "Pro Drupal Development" and "Using Drupal."
"Pro Drupal Development" includes several nice flowcharts and thorough summaries of each of Drupal's APIs (forms, theming, etc.). It's intended to be especially instructive to people making their own modules and themes, but has lots of value to the average PHP-savvy developer who wants to understand Drupal. Besides which, I've created a custom module for every site I've built, just to gain the extra control over things like selectively hiding fields on various forms (which you generally want to do for the sake of simplifying node forms for end-users), so it's good to have this knowledge under your hat.
"Using Drupal" is aimed at the site developer who wants to know how to build the good stuff like galleries, blogs, and social networking sites. It goes through several use-cases and shows how to configure existing modules to do each job. In the process it familiarizes you with the essential add-on modules "Content Construction Kit" (CCK) and "Views," how to make custom blocks and templates, and the ins-and-outs of maintaining a Drupal site. I recommend this book especially for those who want to get up to speed and actually USE Drupal right away. In the process you gain an understanding of the internal organization of Drupal.
New contributor here, 2 years late on the conversation ;-)
Replying to https://stackoverflow.com/a/1070325/1154755
To extend core functionality don't rewrite it. Instead copy the module
into /sites/all/modules/ or /sites/[yoursite]/modules and extend
THAT, or create a new module in those places. Same for themes.
Actually, I never had to copy a core module to update it. Drupal Hooks should be all you need.
For themes, yeah, sometimes it's the only way to go, but often, you can build a subtheme to get the result you need.

Codeigniter In Wordpress Page

Alright, I have a wordpress site, that I want to have a clientportal built with codeigniter in it. For the sake of continued theme, I would like to have the codeigniter program where the page/text would normally be.
Here is the site http://foretruss.com/wordpress/?page_id=8 you can see the error I get when I have php_exec plugin installed and use the snippet.
Any Idea's/help/word of advice?
It's a bad idea to mix and match frameworks like Wordpress and CodeIgniter. There are bound to be collisions of variables and constants; not to mention the substantial increase in resources required to load the page.
If you REALLY need to do this, though, you can try loading your CI setup into a separate directory from your WP setup and use AHAH or an iframe to pull everything over. Granted, you won't get the SEO benefits, but at the same time it's probably the "best" way to go.
For the record, the error that you're getting from CI is a header error. Basically, it's trying to put something in your cookies or write to the HTTP request headers, except they've already been signed, sealed, and delivered (hence the error). Perhaps if you turn off sessions in CI, you'll have better luck. The alternative is to load up the index.php file for WP and put a big
ob_start();
right at the beginning.
See another post on combining CI and WP: Getting posts from Wordpress to out of WP in codeigniter view

Categories