Get wordpress formatted post content without including wordpress functions - php

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.

Related

I am building a Wordpress website with several hundred dynamically generated PHP pages. What would be the recommended way to do this?

My Wordpress website (gcsemathsworksheets.com) will consist of at least 300-400 randomly generated math worksheets coded in PHP. At the moment I am using a shortcode plugin (PHP-code-for-posts) to insert PHP code, but the plugin hasn't been updated for months and looks like it has been removed from wordpress.org.
My options appear to be:
Use a different PHP shortcode plugin
Use custom templates (a new template for each worksheet) as mentioned at https://wordpress.stackexchange.com/questions/73440/how-to-add-a-php-custom-page-to-wordpress?rq=1
Are there other options? What would be the recommended method (in terms of best practices/performance/security etc.)?
Thank-you for your time.
Security:
Code which evaluates other code (as your plugin does) is considered to be a greater security risk; even authors of million user plus plugins can get it wrong https://blog.sucuri.net/2013/05/w3-total-cache-and-wp-super-cache-vulnerability-being-targeted-in-the-wild.html
You have to sanitize input with either method; so using your own page template is likely a safer option.
Performance:
Performance will vary from plugin to plugin dependent on how well designed. A page template with your code is likely to perform better than your code via a 3rd party plugin, but the difference may not be noticeable.
Your description indicates page caching won't be possible. However, under PHP 7 (possibly even on 5.5+) performance is enhanced by using opcache (cached "compiled" copies of your site's scripts) and your site would benefit from this. However code provided via your plugin (and probably its equivalents) is evaled on the fly so and won't be opcached.
I have a single custom page that provides different dynamic content for 2000 different "URL" requests; however these only involve 2 parameters (from one query variable) e.g. WP re-write rules are set to change a request for http://example.com/country/egypt/money into custpage/?queryvar='egypt/money' for delivery of content. I can provide a rewrite example if needed.
Output of your pages may be more complex and depend on many different variables. If so it may be better for performance and simplicity to create separate custom pages to handle the different type of math questions.
Longer term, maintenance and expansion.
Again a custom template is the way to go. Once over your learning curve the knowledge will make it easier for you to enhance and expand your current Wordpress site and others you may wish to set up.
i think best practice is to pass the "random" variables.
And save them to a Database with an id. So if you need the template u generate it in livetime
GET /worksheet/generate/[ID]
MfG R0b1ns

Get WordPress to Read a Custom Database

(Scroll down for question if you don't require background)
For days now I've been working on a project that in simple terms allows users to search an internal company ID and then be shown a load of information relating to that ID (all stored in a SQL db). Just to give you a tiny bit of background, I've always worked with WordPress, I love WP - Custom post types, custom fields, etc - I've always found it to be a good solution for most things.
Now I'm at something of a roadblock. This database that I need a "front-end" to read cannot be changed, it also cannot be moved (/merged with WP tables, etc) as other apps read the same "live" data from it.
I have managed to put together a tiny (sort-of) front end and search function. But I'm still coming across loads of issues, I'm not a pro at PHP/SQL, etc.
My question is:
For me, WordPress seems to to be the best option. How do I get WordPress to "read" from a database entirely separate from WP and "generate" pages based on this data (so that users can search, see info in this custom data, etc), like custom post types/fields but from a db that was never generated via WP?
I understand that a WP table would still be required (but separate) to run the core functions of WP, etc.
Any help would be greatly appreciated!
I think WP is not the best options in this case. Why you don't create a new application using some php/python framework to do that ? It looks like a simple application - just to search App/IDs and show some information.
If you will use WP, I think it will very complicated, because you will have a lot of working making some type of your-sql-version to wp-sql-version and all...
Try some PHP Framework as Laravel( http://laravel.com/) or even Web2py(a simple and good python framework( http://www.web2py.com/). Web2py is really simple and can connect you in your existed database.
Hope it could be useful for you.
The internals of WordPress are heavily customized for the specific databases that WordPress is designed for. Although you could probably force it to do what you want using various hooks and filters, it would be a lot of work and probably fragile.
The most practical approach would seem to be to have WordPress "mirror" your other database.
1) Create one or more custom post types for the type of information contained in your other database
2) Write a synchronization program that takes data out of the other database and creates posts of the appropriate custom type with the imported data as content (and deletes custom posts that are not longer needed). You would need to have some way (e.g. post slug or custom post metadata) for recording which other DB record a given post came from so you did not create duplicates).
The synchronization program would be quite straightforward, and when you were done you would be able to use all of the standard WordPress features with your other data.
Sounds like you're making it more complex than it needs to be. Use http://codex.wordpress.org/Class_Reference/wpdb to read/write to the database and access the tables and data you want, i.e.
$mydb = new wpdb('username','password','database','localhost');
$rows = $mydb->get_results("select Name from my_table");
echo "<ul>";
foreach ($rows as $obj) :
echo "<li>".$obj->Name."</li>";
endforeach;
echo "</ul>";
and use custom page templates http://codex.wordpress.org/Page_Templates if needed to display both the standard WordPress loop as well as the custom data.
Displaying data from that database is one thing; searching is quite another. In order to search that custom data, you will need to run a search with php just on those tables, since they are not standard Wordpress tables and as such aren't searchable by the WordPress site search functions. See Creating a search form in PHP to search a database? In that case, you will need a custom page template to display the php search form and the results.
Wordpress use EZSQL for database connection and it says that you can create more then one connections.
So your first database connection variable is $wpdb, You can create another with different database
$wpdb1 = new wpdb('username','password','database2','localhost');
Now you can query with second database with varisble $wpdb2.
Read more about EZSQL go to justinvincent.com/ezsql

Integrating WordPress into PHP website

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

Can I use Wordpress as an API to load content to my site?

I'm using Wordpress to manage posts in my website, but I don't want to use Wordpress template/visualization. I will use it only to manage the content and program a bit to display the content in my website.
Well, I can access the Wordpress database and load the content with my own queries. But I want to know if is viable to use Wordpress to create the bridge between my site and the Wordpress database.
Simplifying, I want to know if Wordpress provides methods like getAllPosts(), getAllComments that already manage the database connection, queries and returns some objects or I need to build this in my application.
Not native wordpress, but this is very "viable" through plugins. Example: http://code.google.com/p/wordpress-posts-api/ that claims to do what you want for posts, and you could expand to load comments as well - or you may find an exact plug in that you want with a bit of searching.
I've never actually used one written by someone else for this, but have built similar functionality to expose posts etc for XML feeds (then displayed in Flash, for example). Relatively easy if you start with someone else's plug-in and expand.
Just one word of warning - these plugins are great as the operate in the full WordPress environment, so are easy to run. The downside is that they operate in the full WordPress environment, and are therefore inefficient under high stress. If you're going to hammer it, I'd write a caching buffer first, and only make the full call to WordPress when the cache expires.

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