Getting Post Information Outside the Wordpress Loop - php

I know there are functions to like is_single() that will return data about the page, but I'm looking for a way to get the following information outside of the loop:
The category of the single post.
AND
The title of the single post.
All I would really need is the post ID in question and I could get all the other information. I've looked through the functions reference in the codex, but I haven't found anything. Is this impossible because the script doesn't even get that information 'til the Loop runs?
(I would need this information in both the header and footer, so before and after the PHP script for the loop, if that is a problem.)
Hopefully someone can offer some insight.
EDIT: To clarify: I want the information to be from the post that is loaded in the loop on the "single" page. (AKA the post they are viewing.) So how would I get this ID in the first place? Basically, when viewing a post, I want to get its category or title, but not while the loop is going.

This is actually quite simple.
// Gets an array of post objects.
// If this is the single post page (single.php template), this should be an
// array of length 1.
$posts = get_posts();
// The post object contains most/all of the data that is accessible through the
// normal functions like `the_ID()`, `the_author()`, etc
var_dump($posts[0]->ID);
This can be performed outside of and it doesn't affect the normal loop. For example, my single.php template looks like this (line numbers included):
1. <?php
2. get_header();
3. $posts = get_posts();
4. var_dump($posts[0]->ID);
5. ?>
6. <div id="post">

You could execute your own query and return a $post object and then access it's attributes through something like
echo $post->title;
Read about $wpdb and Custom Queries on the Codex. Basically you could run a SQL query using the ID as a where filter through its $wpdb object.
Another option, more WP-like, would be to use a Custom Query Post, where you could define another loop, returning only your post using its id:
query_posts('p=2010'); // 2010 being the post's ID
Then you could run the alternative loop and use the similar $post object to display some information.

This is what I use inside the loop to run an new query; I just tried it outside the loop and it works, on a single.php template page. This will give the title of the latest post in mycategory. I don't know how to pull the category ID, though.
$my_query = new WP_Query('category_name=mycategory&showposts=1');
while($my_query->have_posts()):
$my_query->the_post();
the_title();
endwhile;

After the query has run, try running:
global $wp_query;
var_dump( $wp_query );
The information you are looking for is probably in $wp_query->query_vars or $wp_query->post

You can use the $wp_query global object, and address all returned posts like this
$wp_query->posts ; // contains an array of posts.
Then, if for instance you need to know if the first post is of a certain post_type, you can do this:
$first_post_type = $wp_query->posts[0]->post_type;

Couldn't you store the $post information in a separate variable on the page, then just echo the data you need out later when you need it (ie, outside the loop)?
This is predicated on needing the data after the initial loop has run.

The usual thing is to create "second loop" which would extract needed post, hence your needed data.

Related

Editing serialized data WordPress dashboard

I just inherited a custom plugin that takes Formstack submissions and creates WordPress posts from them. The posts are created fine, however the form contents are stored as serialized data in post_content.
I am tasked with enabling these posts to be edited within the WP Dashboard. Currently when you click on a post title, you are presented with a page that just shows the data; no capability to edit the data.
Enabling the editor controls within "supports" in the functions.php file gives me the editor with the serialized data just dumped in the editor.
I have never had to setup a custom edit page for a specific post type in WP. Is there someone out there who can direct me so a site that explains this? I'm running in circles.
You can filter the content before it is presented in the admin editing screen.
function my_filter_function_name( $content, $post_id ) {
if(get_post_type($post_id) == 'the_post_type_in_question'){
$serialized_content = $content;
$content_array = unserialize($serialized_content);
// do something with this array to put it in the format you want
// .....
$content = $new_formatted_content;
}
return $content;
}
add_filter( 'content_edit_pre', 'my_filter_function_name', 10, 2 );
But, that doesn't seem like it's going to be of much use to you.
In your situation, I suggest you take the time to write a script to convert all those posts so that everything is stored as post meta. (create the custom fields, first).
If your theme isn't built on any framework, then I think the quickest way to create a custom field is to use the Advanced Custom Fields plugin.
Then, once you know the meta_keys, you can write that script. E.g.
$posts = get_posts('post_type'=>'the_post_type','posts_per_page'=> -1);
foreach($posts as $post){
$content_array = unserialize($post->post_content);
// how you do the next bit will depend on whether or not this is an associative array. I'm going to assume it is (because it's a little easier :) )
foreach($content_array as $meta_key=>$meta_value){
update_post_meta($post->ID, $meta_key, $meta_value);
}
// just put what you actually want as the post content back into the post content:
wp_update_post(array('ID'=>$post->ID,'post_content'=>$content_array['post_content'])); // assuming the key of the element you want to be the post content is 'post_content'
}
To run this script, you could simply create a temporary new page and then create a template file specifically for that page and put the above code into that file (then visit the page).
You need to modify the plugin so that the data is unserialized before modifying, then serialized before saving to DB...
Alternatively, try using WP's CORE functionality:
https://codex.wordpress.org/Function_Reference/maybe_serialize
https://codex.wordpress.org/Function_Reference/maybe_unserialize
https://codex.wordpress.org/Function_Reference/is_serialized
https://codex.wordpress.org/Function_Reference/is_serialized_string

Push metadata in array wordpress

Applying meta keys in search result
Since I need to take on a different approach to get my data in javascript from wordpress, I am trying to apply (as follow up on my post earlier today (https://stackoverflow.com/questions/34873986/javascript-for-each-custom-post-type-wordpress)) metadata to my query so it will spit out the right information. This is practically harder than I thought, cause I preferly want it in one query. I been googling now for quite a while, cause I had hoped I wasn't the only one with this problem. I cant seem to find a relevant answer to my problem
Case
Since I was being pointed to the fact javascript and php dont play nice, I was beginning to explore a different way. It requires me to get the results on forehand before I push this into javascript via a json_encode. So far this is running fine, except for one tiny thing. When asking in WP_query I cant get any meta data, which is the part I really need, since that contain map information for my google maps. So is there a way I can query that before I push this through?
<?php
$args = array(
'post_type' => 'hotels',
);
$query = new WP_Query( $args );
echo '<pre>';
print_r($query->posts);
echo '</pre>'
?>
<script type="text/javascript">
var post_info = <?php echo json_encode($query->posts); ?>;
<script>
So far I managed to check what is been given, but I sume, I cant get this via wp_query. Is there another way to actually get the data I need? Or is there a way I can push the meta data in the array with each single post, so I can acces it in Javascript?
Are you looking for get_post_meta() ? https://developer.wordpress.org/reference/functions/get_post_meta/
But you will have to call get_post_meta on each post :/
EDIT :
<?php
foreach($query->posts as $post) {
$post->meta = get_post_meta($post->ID);
}
?>

WordPress global $post variable is empty

I'm working on a wordpress plugin(managing background image), when I try to use
global $post;
print_r($post);
the object is empty.
Probably there is some required data (I dont know what.)
Please help me if you know.
The WordPress global variable $post contains the data of the current Post within the The Loop.
This means that WordPress will assign a value to this variable in each loop iteration. Consecuently, if you're trying to access $post from anywhere in your code outside the WP loop, it will be of course empty...

How can I get an id from a simplepie post which can be used to look it up later?

I've recently started developing a portfolio website which I would like to link to my wordpress blog using simplepie. It's been quite a smooth process so far - loading names and descriptions of posts, and linking them to the full post was quite easy. However, I would like the option to render the posts in my own website as well. Getting the full content of a given post is simple, but what I would like to do is provide a list of recent posts which link to a php page on my portfolio website that takes a GET variable of some sort to identify the post, so that I can render the full content there.
That's where I've run into problems - there doesn't seem to be any way to look up a post according to a specific id or name or similar. Is there any way I can pull some unique identifier from a post object on one page, then pass the identifier to another page and look up the specific post there? If that's impossible, is there any way for me to simply pass the entire post object, or temporarily store it somewhere so it can be used by the other page?
Thank you for your time.
I stumbled across your question looking for something else about simplepie. But I do work with an identifier while using simplepie. So this seems to be the answer to your question:
My getFeedPosts-function in PHP looks like this:
public function getFeedPosts($numberPosts = null) {
$feed = new SimplePie(); // default options
$feed->set_feed_url('http://yourname.blogspot.com'); // Set the feed
$feed->enable_cache(true); /* Enable caching */
$feed->set_cache_duration(1800); /* seconds to cache the feed */
$feed->init(); // Run SimplePie.
$feed->handle_content_type();
$allFeeds = array();
$number = $numberPosts>0 ? $numberPosts : 0;
foreach ($feed->get_items(0, $number) as $item) {
$singleFeed = array(
'author'=>$item->get_author(),
'categories'=>$item->get_categories(),
'copyright'=>$item->get_copyright(),
'content'=>$item->get_content(),
'date'=>$item->get_date("d.m.Y H:i"),
'description'=>$item->get_description(),
'id'=>$item->get_id(),
'latitude'=>$item->get_latitude(),
'longitude'=>$item->get_longitude(),
'permalink'=>$item->get_permalink(),
'title'=>$item->get_title()
);
array_push($allFeeds, $singleFeed);
}
$feed = null;
return json_encode($allFeeds);
}
As you can see, I build a associative array and return it as JSON what makes it really easy using jQuery and ajax (in my case) on the client side.
The 'id' is a unique identifier of every post in my blog. So this is the key to identify the same post also in another function/on another page. You just have to iterate the posts and compare this id. As far as I can see, there is no get_item($ID)-function. There is an get_item($key)-function but it is also just taking out a specific post from the list of all posts by the array-position (which is nearly the same way I suggest).

How to get id of post inside of plugin

I want to retrive post id inside plugin.
I tried
global $post;
$a_Id=$post->ID;
and
global $wp_query;
$thePostID = $wp_query->post->ID;
and
var_dump(get_the_ID()); //shows just null
How i can retrieve it?
The idea is to get language of post from Custom Fields
and feed it into Global Translator plugin as a BASE LANG
EDIT:
I can retrive id from $_GET['p'] on development server but on production i
have pretty urls so i dont have it.
Assuming that you know what the ID is for an particular post you could use
var_dump(get_defined_vars());
to show a listing of anything that you can get your hands on.
Look through the output for the ID that you know and then use the path that it shows to get there.
What are you doing with the post ID? When exactly do you need it? I'm guessing you are using this very early in your plugin file, when the query is not yet parsed. The query is parsed after the hook parse_query is fired.

Categories