I want to write some simple code to figure out if the user is the author of any posts (Not if their role is author)
My attempt is as follows but I can't figure it out
I got the userID (set it to current in global header)
I have created a query to for custom-post-type and author
I have got all the current posts from the query
I have added an IF statement (Which I CANT seem to get right)
Here is my code try
<?php
// Global variable for current user ID
$user_ID;
// Create a new WP query object
$my_query = new WP_Query( array(
'post_type' => 'farmers',
'author' => $user_ID
));
// Get all the current user posts from the query object
$posts = $my_query->posts;
IF There are Posts (Not sure how to write this line) {
// Do something
} else {
// Do Something else
} ?>
Thanks for any help guidance
How about:
if( $posts ) {
// Do something
}
else {
// Do Something else
}
Related
Having a bit of an issue and hoping for some help. Basically I am triggering a function on acf/save_post action for a custom post type called 'settings'. So if 'settings' is saved or updated I want to loop through all existing pages and update a ACF field for each page with a specific piece of data. My loop is below. I've been fighting with this thing all weekend but it doesn't seem to update any pages. Any help would be huge! Thanks!
$the_query = new WP_Query( array( 'post_type' => 'page' ) );
while ( $the_query->have_posts() ) : $the_query->the_post();
global $post;
$pageID = $post->ID;
update_field('temp_post_data','test' , $pageID);
endwhile;
You are trying to update field on current page.
Try this
function my_custom_function() {
$pages = get_pages(); // get all pages
foreach($pages as $page):
// error_log($page->ID); // debug if needed
update_field('temp_post_data','test' , $page->ID); //for each page we are updating field
endforeach;
}
I am developing a plugin. In this plugin, I've created a custom post type 'toto'.
In the admin page, I edit a custom post element with the following post id '82'.
In this page, I launch a query to retrieve elements with another post_type like that :
$featured_args = array(
'post_type' => 'other_type',
'post_status' => 'publish'
);
// The Featured Posts query.
$featured = new WP_Query( $featured_args );
// Proceed only if published posts with thumbnails exist
if ( $featured->have_posts() ) {
while ( $featured->have_posts() ) {
$featured->the_post();
if ( has_post_thumbnail( $featured->post->ID ) ) {
/// do stuff here
}
}
// Reset the post data
wp_reset_postdata();
}
Doing that the global $post changed. It is not the post with the id 82 anymore but the latest post element from the query.
I thought that the wp_reset_postdata() function will allow me to retrieve my current $post. I also tried with wp_reset_query() without changes.
Am I missing something?
Any help would be appreciated.
wp_reset_postdata() resets the main loop. If you want to access $post directly try
global $post;
$backup_post = $post;
//do another loop
wp_reset_postdata();
$post = $backup_post;
This is fixed thanks to Alex's answer below.
So this is a bit of a weird one. I am setting up so I have category's with names "cat1, cat2, cat3" etc.
And say I had users called "cat1, cat2, cat3" so they matched the same as the category names.
I am then wanting to somehow only show the posts to the user that relates to their category, so basically if USER: "cat1" is logged in then they could only see the posts in category "cat1" as it matches their username.
I know you can do this to show posts only that the current user logged in has made but this wont work as the way the posts get put into the category complicated to explain.
<?php
// The Query
$args = array(
'post_status'=> '.....'
);
global $user_ID;
get_currentuserinfo();
if($user_ID) {
query_posts( $args,"author=$user_ID" );
}
?>
So if anyone has any insight into only showing posts to a user that matches a category with the same name as the user logged in hopefully they will be kind enough to help out.
It seems like you've started a round-about way of getting this accomplished. Since you have categories already set up with the username, you should just be able to place that in your query
//Get User -> ID -> Cat
global $current_user;
get_currentuserinfo();
$args = array(
category_name => $current_user->ID
); //or use $current_user->display_name if that's how they are set up.
// The Query
$the_query = new WP_Query( $args );
// The Loop
while ( $the_query->have_posts() ) : $the_query->the_post();
//Display your loop how you want
endwhile;
// Reset Post Data
wp_reset_postdata();
EDIT:
did you do var_dump($current_user->ID) to see if it matches the category name? That variable from the object might only contain an ID (like "1" or "178" etc). If that was the case, you'd need something like
$the_cat_name = 'category' . $current_user->ID;
//Append your 'naming structure' to the front of the user ID
Then just replace the array with
$args = array(
category_name => $current_user->ID
);
Alternatively, look at the Current User Functions (here). You may be able to use
$current_user->user_login
instead. You could also just try var_dump($current_user) (after calling global $current_user; get_currentuserinfo();) and see what variable contains the string you need
UPDATE: I have tried using the following code:
<?php if (is_category(events)) {
$posts = query_posts($query_string . '&orderby=event_date&order=desc');
} else {
$posts = query_posts($query_string . '&orderby=title&order=asc');
}
?>
Is there any reason why that wouldnt work? It seems to work fine organising posts in alphabetical order, but still no luck on the date order within 'events'.
--
After searching through various existing questions I can't quite find a solution to what I am trying to do.
Currently all posts on my site are ordered alphabetically, which is fine except for one new category that I have added. For this category I want to order all posts by a value that I enter into a custom field. The field is called 'event_date' - so I want to order the posts by date essentially, but not the date the post was created, the date the user manually enters into this field.
I managed to get it working by using:
<?php if (is_category($events)) { $posts = query_posts($query_string . '&orderby=$event_date&order=asc'); } ?>
However this overrides the aphabetical order for all other pages.
For alphabetical order I am using:
<?php if (is_category()) { $posts = query_posts( $query_string . '&orderby=title&order=asc' ); } ?>
Essentially I want a statement that tells the page to order all posts in aphabetical order, unless the category is 'events', where I want to order them by the custom event date.
As you can probably tell I'm very much front end, not back end so a lot of this is fairly new to me, so any help or advice is appreciated.
To order posts by a custom field value, you need add the custom meta field to the query itself. orderby=meta_value in addition to meta_key=metafieldid will allow ordering in this fashion.
I would use the pre_get_posts hook and modify the query object if get_query_var( "cat" ) (or a similar query var) returns the desired post category.
add_action( "pre_get_posts", "custom_event_post_order" );
function custom_event_post_order( $query )
{
$queried_category = $query -> get_query_var( "cat" );
/*
* If the query in question is the template's main query and
* the category ID matches. You can remove the "is_main_query()"
* check if you need to have every single query overridden on
* a page (e.g. secondary queries, internal queries, etc.).
*/
if ( $query -> is_main_query() && $queried_category == 123 )
{
$query -> set( "meta_key", "event_date" ); // Your custom field ID.
$query -> set( "orderby", "meta_value" ); // Or "meta_value_num".
$query -> set( "order", "ASC" ); // Or "DESC".
}
}
Remember that this approach overrides all queries that are using the category in question. You can build custom WP_Query objects that use their own parameters for constructing loops.
You also should standardize the way you save the custom field data to the database. For dates I prefer using UNIX-timestamp formatted times that are easy to move around and manipulate. This way no accidents happen when querying and some data is formatted in another way that the rest is.
Disclaimer: I did not have the time to test the above code in action, but the general idea should work properly.
EDIT: of course the above code should be inserted to functions.php or a similar generic functions file.
What about:
<?php $posts = query_posts($query_string . (is_category($events)?'&orderby='.$event_date:'&orderby=title') . '&order=asc'); ?>
<?php
$recent = new WP_Query(“cat=ID&showposts=x”);
while($recent->have_posts()) : $recent->the_post();
?>
Hopefully I understood your question, use the WP_Query and within the orderby add a space between your order by columns:
$args = array(
'posts_per_page' => 100,
'orderby' => 'title',
'order' => 'ASC',
);
if(is_category($events)){
$args['orderby'] .= " meta_value_num";
$args['meta_key'] = 'event_date';
}
$posts = (array) new WP_Query( $args );
I have the following function that I've added to my functions.php file in WordPress. The idea is that it gathers all of the titles of 'fsmodel' posts (a custom post type that I've created). It then returns these as an array, which I then use to populate a select tag in the custom meta fields for a second custom post type.
Basically, 'fsmodel' will have posts with a boat model, and the 'fsboat' post type will have a drop-down with the names of each of the models to select from.
Now, this appears to works fine in the Dashboard - the drop-down is populated as expected. When I save, however, the post doesn't show up in the Edit list. Also on the website, all pages output as the 404 error page when this function is active.
I'm certain that the problem lies within the following code - does anyone have any idea what I might have done wrong?
function fs_model_array() {
$models_array = array();
$loop = new WP_Query(array(
'post_type' => 'fsmodel',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'post_status' => 'publish'
));
while ( $loop->have_posts() ) : $loop->the_post();
$models_array[] = get_the_title();
endwhile;
return $models_array;
};
OK, I've come up with a solution (I hope - it's holding up for now).
Instead of creating a loop, I've just used the $wpdb->get_results to search the database for the column with a WHERE filter for the custom post type.
Then run an array builder:
$models_array = array();
$model_db = $wpdb->get_results("SELECT post_title FROM $wpdb->posts WHERE post_type='fsmodel' AND post_status = 'publish'");
foreach ($model_db as $model_db) {
$models_array[] = $model_db->post_title;
}
Thanks again for your time, hsatterwhite! :-)
I think you might find that adding wp_reset_query() to the end of your function will solve your problems :)
I like your solution, but I'd be inclined to say that you need to call the global variable of $post whenever you use the loop like this in a function, as it assigns it to that variable.
function fs_model_array(){
global $post;
$models_array = array();
$loop = new WP_Query(array(
...