Wordpress Loop get_the_id() - wordpress

I tried the following functions in header.php, footer.php, single.php etc.
var_dump(in_the_loop());
var_dump(get_the_id());
The first function gives false (meaning we are not in the loop) and the second function gives the post id every single time.
Description of get_the_id() from wordpress :
Retrieve the numeric ID of the current post. This tag must be within The Loop.
I just want a simple explanation what the hell is going on why do i get the post id if I call the function out of the loop !?

must is a little strong for get_the_id() ...delivers evil eye to Wordpress.
It works in the header and non-loop (confirmed).
Please note that post/page are essentially interchangeable in this conversation.
Think of WP this way -> You always have a post id in some way, all the time, every page, unless you do weird stuff or talk about non-page edge cases. When you are at the install root (such as site.com/) there are posts being called, something has to be displayed. There are other settings that will impact post/page such as static front page settings. On a category listing, if there are pages, I got the first ID returned before the loop.
On post/pages the page ID is (more or less0 set before the loop. This is a result of the URL (pretty or ?p=123 format) dictating the content. Using pretty names, the page at site.com/foo-bar/ will try to look up if there is content available via the permalink rules for "foo-bar". If there is content, the post ID is obtained. (simplified)
Later in the page build you get into the loop. However, before the loop you are also offered opportunities to change, sort, or augment the loop - such as changing the page IDs to be looped or sorting.
Regarding in_the_loop(), WP says
"True if caller is within loop, false if loop hasn't started or has ended." via http://codex.wordpress.org/Function_Reference/in_the_loop
in_the_loop() evaluates if the loop is in action (loop being key to the WP world). Also important - when you are in the loop WP can iterate over multiple page/post (IDs).
I don't have a 100% bulletproof explanation as to how the ID always shows, but when you dig into the API and various methods for hooking this might be a result.
I understand your confusion and agree with you. I think WP intended get_the_id() as a loop based tool, outside the loop you will get unpredictable results.
Hope that helps, I do enjoy working in WP, and I hope you do to.

Related

How can I exploit the wordpress template hierarchy to render a different post template depending on category name/slug?

Apologies if this appears simple to some, but I have scaled high and low and I'm not finding a solution here to my problem, which is:
I have a website set up with Wordpress in which posts can fall under one of three categories: reviews, views, news - the slugs associated with each of these category names are the same.
Currently, calling up the web page of any individual post classified under any of these categories will see it rendered by the file single.php.
However, I want to make a slight adaption to the rendering of the post when it falls within the 'reviews' category. I have copied and renamed the original single.php file to single-post-reviews.php (no custom posts here, I will just confirm and I would like, if possible, to avoid child-theming here - not good practice, I know), but I am not seeing the new rendering from my new file.
I've also tried renaming to single-reviews.php which hasn't worked either - so could someone tell me what exactly I'm missing here?
Thanks,
WordPress Template Hierarchy for Single Posts doesn't factor in the current post category (likely due to the fact you can have multiple categories). Due to this, you have 2 viable options to your problem.
1) You can modify single.php to check for the post category, and if it's categorized under reviews, do something. This makes sense if you're just adding a small amount of markup in one or two places, or even hiding a few lines conditionally.
2) You can override the page template that's loaded based on the post's category using the single_template filter. Because I don't know exactly what you're doing, I'm going to elaborate more on this method. Take the following function:
add_filter( 'single_template', 'so51913799_review_template' );
function so51913799_review_template( $single_template ){
global $post;
if( has_category( 'reviews' ) ){
$single_template = get_stylesheet_directory() . '/single-post-reviews.php';
}
return $single_template;
}
If you put it in your functions.php file, it will make use of the has_category() function (I prefer this to in_category() since in_category just returns has_category anyways) and if it matches, it will update the $single_template variable to single-post-reviews.php. This assumes that the file is inside your /wp-content/themes/ACTIVE-THEME/ directory.

How do I test for an invalid WordPress WP_Query query?

I have a page template which displays a list of post summaries, depending on a user-defined custom query, which is supplied using the post_content, for example:
category_name=blog
This is then passed to WP_Query() which will return however many 'blog' posts there are.
However, if I pass a completely invalid query (or simply make a mistake) such as:
the rain in spain falls mainly on the plain
WP_Query->get_posts() will return ALL posts in the database, rather than letting me know that the query is meaningless / erroneous.
Is there a built-in method to test for invalid queries?
Currently, I'm doing a parse_str() to convert the query to an array, then an array_intersect_keys() against a list of valid query parameters I've compiled from the WP_Query page.
It works, but feels pretty hacky - am I missing something?
Thanks,
Dave
I don't believe there is a failed query catch built in to WP like you are asking for (I wish there were, too).
However, there may be a cleaner hack. wp_count_posts will return a count of all posts in the database. And wp_query will return a count of its results in $post_count. One thing you could do is a check on your query - if the result of wp_count_posts is equal to $post_count then you know something is wrong.
It's not as clean as a 'no results' response, but perhaps more straight forward than your current solution.
http://codex.wordpress.org/Function_Reference/wp_count_posts
http://codex.wordpress.org/Class_Reference/WP_Query (search the page for $post_count)

Merge comments between different posts

I need to replicate the behavior of this site:
http://www.theincipit.com/2013/11/la-notte-di-halloween-tost/9/
As you can see, I linked a "story" divided in various chapters (1-10). Every single chapter, though, displays the same list of comments. So you can comment every chapter but it will go automatically under the same list, displayed in every chapter.
In my site I have different posts grouped in different categories, and I''d like that the same posts form one category display the same list of comments (and when you comment from every post of that category, you update the same list)
Thanks!
Here's a start, anyway. Haven't tested this, yet.
add_rewrite for to get an extra querystring
Add a rewrite to the specific page (id as XX, below).
add_rewrite_tag('%chapter%','([^&]+)');
add_rewrite_rule('^story-slug/([^/]*)/?','index.php?page_id=XX&speaker=$matches[1]','top');
make a template for that specific page.
And create a page-xx.php where xx is the page ID (or slug) that will make use of an extra piece on the end of the url: /story-slug/1/ the 1 in this case. Don't forget to include the comments in this template!
In the post editor, write the whole thing as one entry, wrapping the chapters in [chapter id="X"]
Then, hide chapters that don't correspond to the url's chapter query, via shortcode.
add_shortcode('chapter', 'chapter_display')
function chapter_display($atts, $content) {
$current_chpater = $wp_query->query_vars['chapter'];
$chapter = $atts['id'];
if ($chapter == $current_chapter)
return $content;
}
Only thing missing from this solution is pagination across the top / bottom.
By continually referencing the same post, but showing different parts,
PS - don't forget to hit up wp-admin/options-permalink.php to flush the rewrite rules after you add the the add_rewrite_xxx functions to make sure that they take.

updated_{$meta_type}_meta not firing, but updated_post_meta is

I'm not sure if I'm using it correctly, but I can't get the updated_{$meta_type}_meta hook to work. There is a updated_post_meta hook which runs when you save a posts meta (and possibly other times, I haven't checked). I can't find much reference to updated_{$meta_type}_meta apart from here, so I don't really understand if I am even hooking it correctly, because I didn't read it properly at first and so thought it should be used like: updated_CPT_meta, but that didn't work, so I tried a meta key instead of the CPT.
My question is, what should $meta_type be ?
Of course I found this straight after I posted
As the page at https://core.trac.wordpress.org/browser/tags/3.8.1/src/wp-includes/meta.php#L0 states, $meta_type Type of object metadata is for (e.g., comment, post, or user).
So, you should just use it as updated_post_meta for any CPTs also.
duh.

How to restrict text length of a field while in WordPress editor?

I would like to restrict the fields while creating a new post in WordPress. For the title, it should not exceed 40 characters. For the content, it should not exceed 400 characters. If these maximum values are exceeded, I would like to show an error message and not let the user continue. How do I do that in WordPress?
You should be able to use wordpress filters to modify the code that gets outputted when the editor is called. Essentially you would want to use it to insert some javascript and an extra div tag to display your error, then just read the contents of the "editorcontainer" id and show the error once it reaches a certain character limit.
I don't have the time at the moment to write a case example, but depending on your skill level, the functions you are looking for are:
apply_filters("the_editor", "customfunction_limitarea");
Where customfunction_limit area is your created function to insert the javascript. You can see how the_editor is currently called and how the default filters are applied in "wp-includes\general-template.php" on line 1822. The default looks like this:
$the_editor = apply_filters('the_editor', "<div id='editorcontainer'><textarea rows='$rows'$class cols='40' name='$id' tabindex='$tab_index' id='$id'>%s</textarea></div>\n");
I would try modifying that statement by placing a new filter in a functions.php file located in your themes directory, that way you don't have to worry about it getting over-written during an update. Otherwise, if you absolutely have to edit the wordpress core (generally a no-no), general_template.php would be the place to do it I think.
Essentially just read up on wordpress filters a little bit (be warned there's not a ton of documentation or examples available for it other than the basic stuff), and that should provide everything you need. The input verification end is easy enough to find scripts, just google jquery post limiting. Something like this might be exactly what your looking for:
http://swiki.fromdev.com/2010/02/jquery-maximum-limit-texttextarea-with.html

Resources