Find from where the data comes to "the_content()" function - wordpress

This might look an ordinary question though I'm stuck in it. I'm new to the wordpress. I've bought a wordpress theme and I'm trying to edit some pages as I want. Now I want to edit the default post page where I've already started editing the "single.php" and "post-format.php" files. I want to know from where or how "the_content()" function gets data?
Since I want some html part of the page to be removed though that html part comes through a "the_content" function. Therefore, I'm unable to remove that part without getting rid of "the_content" function. But I can't get rid of "the_content" function because the very same function calls some important part too.
Hope you guys can help!

From Where
As a function get_the_content() retrieve the post content (Generally Used in a Loop) from database and prints on the frontend.
And again the_content() as filter controls how you show the post content.
How
Dead simple answer by WordPress API. You need to understand WordPress Database_API for in-depth understanding.
Frequently Used by
wp-includes/plugin.php: apply_filters()
wp-includes/post-template.php: get_the_content()
wp-includes/post-template.php: the_content
Usage Case: (from Codex)
post_password_required()
get_the_password_form() if post_password_required() fails
wp_kses_no_null() while processing the tag.
balanceTags()
get_permalink()
global: $id, $post ,$more, $page, $pagesm, $multipage, $preview, $pagenow
Ref:
- Filter the_content() | Functionthe_content()
Optional: Offline WP Codex Docs Search/Browser for Windows/OSx

Related

No other way to put this: How do I use The Loop?

I apologise for this post being so long. The REASON for me asking such a stupid question as the topic suggests is BECAUSE there is just so many different things going wrong that I need to provide details of WHY I am asking this question.
Please bear with me...
I am busy creating a custom theme for my personal use have a LOT of slug-based pages and I use WP_query a lot(!) for many things from a custom news ticker to procedurally generating my navbar to mention but a few.
I was under the impression that creating a custom WP_Query means the content inside the results will not interfere with the operation of the main Loop and yet, I get very strange behaviour...
All my custom slug-based pages always work perfectly fine but when I use this in my navagation.php template part:
$query = new WP_Query($args);
if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post();
//do my stuff here
endwhile; endif;
...this results in pages and posts loading just fine during the Loop but when I get to the product I am trying to view it always shows the same product no matter what link I follow. Eventually I added this to the product page:
if (have_posts()) {
the_post();
rewind_posts();
}
...and that made the products load up just fine. Yeay! No idea WHY I have to do it but it works. Strangely enough, though, in the template, just before it loads the template part that does the product layout, I print the name of the post currently in the global $post and then watch as it prints the wrong name above the right product after starting the Loop. (!?)
So then I find out about get_posts() and I like the fact that it gives me an array rather than an object that contains an array and so I swap over to using get_posts() in my navigation.php header template part and now my header section still works perfectly and my products display perfectly... but all posts and pages now show the same content. All posts and pages now show the same WooCommerce product. (!?) What's more confusing is that I do 3 WP_Query calls in navigation.php and the Loop in my posts and pages all show the first entry from the FIRST query, not the last...
After much struggling I decided it wasn't worth the aggravation so I swapped back to using WP_Query. Now things are all messed up in ways I can't even begin to understand... Now my posts and pages work just fine (so does my custom menu) but my products now all show the same product while in the loop. I tried doing this:
global $post;
$current = $post;
//do my query and loop over it
$post = $current;
Somehow that code turns the $post (which is just a pointer into the array) into an array itself (or something) because the product template now first displays the same product on every page I go to and then it displays the $post product it was supposed to directly below it. If I set $post to null directly after I set $current then setting $post back to $current afterwards results in only the wrong page showing up.
Somehow I managed to get it to stop showing the wrong product and now, instead, only my slug-based pages work because anything that uses the Loop (post, page and product) just tells me this:
Fatal error: Uncaught Error: Cannot use object of type WP_Query as array in D:\xampp\wordpress\htdocs\wp-includes\class-wp-query.php:3071 Stack trace: #0 D:\xampp\wordpress\htdocs\wp-includes\class-wp-query.php(3099): WP_Query->next_post() #1 D:\xampp\wordpress\htdocs\wp-includes\query.php(805): WP_Query->the_post()
..and tracking the stack trace to where that occurs seems to indicate that (apparently) I am trying to use a WP_query as an array when I say this during the Loop:
if (have_posts()) : while (have_posts()) : the_post()
How is THAT code wrong? It's straight from the manual! :O
According to the Codex, even though get_posts() also uses WP_Query it allows you to have multiple Loops and it says that you should use the restore_post_data() (I think) IF you updated the main Loop contents. But I am NOT trying to modify the main Loop at all. I want to do a query, have the results in a variable, run over that result and then discard the variable before going into the Loop and showing the page content as normal. I want my queries to run independently of the Loop and NOT in any way interfere with the operation of the Loop at all.
So:
why the heck does my custom WP_Query calls interfere with that I am seeing in the Loop and
why the heck do I get the error about trying to pass a WP_Query object as an array when calling the default, vanilla Loop
why do my products display correctly but my posts and pages do not
or why does my post and pages show correctly while my products show two different products
How the heck can my fully functional site get THIS broken just by going from $posts = get_posts($args) to $query = new WP_Query($args) ???? In a separate job completely outside the Loop, no less!
It makes absolutely no sense and since it makes no sense I have no idea where to start when trying to implement a fix. So what am I not seeing here? rewinding the posts, restoring the post data... nothing helps. I am completely dumbfounded.
Am I not using the Loop correctly? All I want to do is this:
Load a page that does a custom WP_query and displays the content
Load the template part that performs the Loop (i.e. single-product)
Display the template part that page loads (i.e. content-single-product) and have it be the right content
It shouldn't be this hard, should it?
Such a simple little thing to cause such a massive amount of grief... :(
Inside my navigation template part when I made the switch back from get_posts() to WP_Query I stored one query in $posts and the other in $query. Seems $posts is a reserved variable in WordPress because the moment I changed $posts to $query also everything worked 100% perfectly again!
I was aware of $post but not $posts. Now I know. Special thanks to #zipkundan for pointing me towards wp_reset_postdata(). That page taught me that custom queries DO in fact affect the global Loop (News to me!) and showed how to work around it.
So basically, the problem with my posts not showing what they were supposed to was due to me not calling wp_reset_postdata() after running through my custom loop and the reason for all the inexplicable weird page anomalies was due to me saving my custom query to a reserved variable name.
Mystery solved.

Should I use wp_reset_postdata() or just save the global $post variable myself?

I have a Wordpress 4.3 site that uses Yoast for SEO. I have a custom post type and a shortcode that can be used to generate a list of posts of that type. The shortcode function uses what I believe to be the recommended approach in Wordpress for generating a list of posts of a certain type:
$query = new WP_Query(...);
while ($query->have_posts())
{
$query->the_post();
// Now I can call methods like the_ID(), the_permalink(), etc
// I can also access details of the post directly, because at
// this point it is stored in the global $post variable.
}
wp_reset_postdata(); // To restore original copy of global $post variable
When viewing the actual page that contains the shortcode, everything works fine because the global $wp_query variable stashes a copy of the global $post variable before the shortcode function gets called, which enables wp_reset_postdata() to successfully restore the state of the global $post variable.
However, I recently discovered a problem when editing the page and although I have fixed the issue, I would like to know if my solution is correct practice in the Wordpress world.
The problem was that whenever I edited the page, several fields would get changed without me having actually touched any of the settings. Further investigation revealed that the reason for this was that the HTML for the edit page, specifically the contents of some form fields, had already been altered by the time they reached my browser. Compounding this problem was the fact that the permalink field, which is highly visible, was not being altered, but a hidden field called slug was being altered, and so when the page was submitted, Wordpress was updating the permalink with the value of this now corrupted, hidden slug field. My permalink wasn't so perma after all!
The only clue I had about what was causing the problem was that the permalink that was being set belonged to another post; in fact, one of the posts that comes up when the shortcode function gets executed.
After a day and a half of debugging, I figured out the precise reason why the form fields were being trashed:
When preparing the edit page for a post, Wordpress calls all the related plugins in case they need to add any additional information or controls to the sidebar.
One such plugin is Yoast, which reports an SEO Status. In order to calculate this status, Yoast silently renders the post so that it can then analyse the contents of the page, taking into account the focus keywords, etc.
In order for Yoast to silently render a page, all of the shortcode functions that contribute output to that page must also be executed.
When my shortcode function gets executed as part of Yoast's silent page rendering, it does what I beleive to be the right thing by calling wp_reset_postdata() at the end to restore the contents of the global $post variable.
However, the problem was that wp_reset_postdata() was not, in fact, restoring the global $post variable, because the global $wp_query variable did not have a copy. I would have expected wp_reset_postdata() or WP_Query->reset_postdata() to throw an error at that point, but they don't.
So every form field in the edit page that was generated after Yoast did its work ended up with values from the wrong post, because the global $post variable had been left with the wrong contents.
I have resolved the problem by adding the following defensive/unobtrusive code to the top of my shortcode function:
global $wp_query;
if ( $wp_query->post == null )
{
return '';
}
This means my shortcode function will only execute "the loop" when there is a guarantee that it will be able to restore the global $post variable using wp_reset_postdata().
Should I stick to this solution or take it one step further and simply save a copy of the global $post variable myself and just ignore wp_reset_postdata() altogether?

Wordpress: How to pass additional Content to the blog-preview page?

For each blog-post on my wordpress-blog I'd like to have Teaxtarea where i can pass additional content for that post.
In my case that would be an unordered list which contains a quick overview of the content.
That additional content should be displayed in the preview of the post on the blog-preview-page.
My problem:
I am actually not sure on how to best add this additional content and then pass it to the preview.
Do I use wordpress' custom fields for something like this?
I'm gratefull for a push in the right direction.
Thank you,
Nils
If I understand you right, I'd take a look at "custom meta boxes" functionality - it allows you to add any type of additional input into your blog post admin area, and than display its content on front-end however you like.
There's a nice tutorial series on that topic, with example code snippets:
http://wp.tutsplus.com/series/reusable-custom-meta-boxes/
And if you'd like to display the textarea content only in preview mode, you can use appropriate conditional tag in you template file:
http://codex.wordpress.org/Conditional_Tags#A_Preview
The conditional tag is_preview returns true when a single post is viewed in Draft mode. The following will append post meta to the content when a post is being previewed:
function so16799607_preview( $content )
{
if ( ! is_preview() )
return $content;
return $content . get_post_meta( get_the_ID(), 'my_post_meta', true );
}
add_filter( 'the_content', 'so16799607_preview', 10, 1 );
You should check out Advanced Custom Fields. That's a really stable plugin that lets you create custom meta boxes in posts, pages and custom post types. That plugin does exactly what your question states. Need al little PHP to get stuff from your database, but that is as easy as:
<?php the_field(field_name);?>
And the documentation is pretty good. And if you don't like a plugin, it exports the PHP as well.
Anther tool that does the same is Pods Framework. Both powerfull extensions to any WP install in my opinion.
Hope this helps.

WordPress functions.php: how to apply update_option()?

I'm trying to set the default Image Link URL for my WP users so that it doesn't include the url link as a default. I've done some research, and I know the function is in the wp-admin/options.php:
update_option('image_default_link_type','file');
Rather than mess with the core files, I'd like to put this into the functions.php, but never know the proper way to implement stuff like this! This is what I have so far in my functions.php:
<?php
update_option('image_default_link_type','none');
?>
This obviously doesn't work: it needs the proper setup! What is the correct way to implement this in functions.php?
Also: I'd like to know the strategy for figuring out how to implement functions like this in the future by myself? For example, I never know whether or not I'm supposed to use add_filter or do_action, and how I need to pass the parameters. I've yet to find a book or post out there that explains this very well, and can show me by example. Any good leads on this would be awesome too!
Start with the Wordpress codex. Visit the plugin API (which is really what you are doing) that explains Hooks, Actions and Filters. Then see the Action Reference which provides your list of hooks.
Here you will find the hook update_option_OPTIONNAME. Description from codex:
Runs after a WordPress option has been update by the update_option
function. Action function arguments: old option value, new option
value. You must add an action for the specific options that you want
to respond to, such as update_option_foo to respond when option "foo"
has been updated.
Adding code from asker's comment:
function inventory_linkurl_setting() {
update_option('image_default_link_type','none');
}
add_action('admin_init', 'inventory_linkurl_setting'); ?>

Wordpress: apply_filters & add_action to the_content = EVIL?

I asked this question over in the actual tutorial, but not sure I'll get an answer anytime soon as it's almost 2 months old... so I'll take a gander here...
Tutorial is here: Build a WordPress Plugin to Add Author Biographies to your Posts
To sum up the tutorial and what the problem is, The tutorial adds an Author Bio on to the end of the content like so (the short version):
function x($content) {
return $content . "Author Bio";
}
add_action('the_content','x');
The Problem:
When someone uses:
$z = apply_filters('the_content', 'some content here');
echo $z;
The Author Bio will end up applied to $z and if $z is echoed out in the middle of some page… the Author Bio would be in the middle of some page… correct? (it's correct because I've tested it...)
Is there a better way to apply something to the end/under/below the_content hook? other than add_action(‘the_content’, ‘some_function’) because this to me seems evil...
or is apply_filters(‘the_content’, ‘some content here’) not the norm or something developers shouldn't be using inside their WordPress templates…? (which seems pretty much the norm, at least upon Google-ing formatting "the_content" outside the loop)...
Using apply_filters('the_content','some content here'), while it may not be 'the norm' (I don't know. I haven't seen it before, but if I needed formatted text, that's what I'd do), is a perfectly valid use of filters to get some text formatted like the content. Unfortunately, there's no better way to append something to content from a plugin. That is just the way these things work.
However, there's a (less than optimal) way of circumventing this. As part of the setup/install process for your plugin, have the user insert a custom function call, action, or filter into their theme. I know several plugins that do this, so it's not all that uncommon. Something like this:
do_action('my_super_awesome_bio_hook');
Would allow you to hook in without worrying about adding a bio to unexpected (and unintended) content. Even better would be inserting a filter:
echo apply_filters('my_super_awesome_bio_filter_hook','');
That would allow your plugin to modify the bio, but also allow the one using the plugin to override it if necessary (like on pages where they're just using excerpts, like search results, etc.).
Hope this helped.
Also, one minor addendum: you should be using add_filter, not add_action to append the Author Bio. add_action still works, but it's a filter you want to be using.
I bumped into a similar issue with a widget I'm dev'ing. I just found this:
http://codex.wordpress.org/Function_Reference/wpautop
Which I'm now going to use instead of add_filters('the_content'). I want the WYSIWYG formatting but I don't want things append to my content because it's not traditional content anymore.

Resources