wp_query in add_action( 'admin_notices' - wordpress

I have a custom post type - "data-result" of which there are 5 published posts.
I have another post type "data-collection-tool" that creates a "data-result" post from the front end when a user visits/edits a 'data-collection-tool' post and this works well.
I want to display a notice in the dashboard when the admin tries to edit a "data-collection-tool" post but where there a one or more "data-result" posts.
Code
function ws48356743_warn_questionnaire_editor() {
if(get_post_type() == 'data-collection-tool' ){
?>
<div class="notice notice-warning is-dismissible">
<p><?php _e( 'Done! '.wp_98435409_checkResultsExist(get_the_ID()), 'sample-text-domain' ); ?></p>
</div>
<?php
}
}
add_action( 'admin_notices', 'ws48356743_warn_questionnaire_editor',1,0 );
To do this I am querying "data-result" in a separate function:
function wp_98435409_checkResultsExist(){
$args_n = array(
'post_type ' => 'data-result',
'post_status' => 'publish',
'posts_per_page' => 9999
);
$p = get_posts($args_n);
print_r($p);
wp_reset_postdata();
}
get_posts returns an empty array and I can't figure out why.
All of the above code runs in functions.php
Does anyone have any pointers?
Thanks

A rogue space stopped this working
$args_n = array(
'post_type' => 'data-result', // <- was here in 'post_type '
'post_status' => 'publish',
'posts_per_page' => 9999
);

Related

Why wc_get_template_part() not working inside wc_get_products()?

Cant find full loop example on the web with wc_get_template_part() and wc_get_products(), so looking for help here:
global $woocommerce;
global $product;
$args = array(
'limit' => 15,
'category' => array('printers', 'laptop')
);
$query_cats = wc_get_products($args);
foreach ($query_cats as $query_cat) {
echo $query_cat->get_id();
echo $query_cat->get_title();
// echo "<pre>";
// var_dump($query_cat);
wc_get_template_part('content', 'product');
}
?>
Titles and ids are displayed, var_dump also, bu wc_get_template_part - no. I have add_theme_support('woocommerce'); and also body_class();
WooCommerce content-product.php template only works only with standard loop(with instance of Wp_Query). May be following solution can help:
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'tax_query' => [
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => ['printers', 'laptop'],
)
],
);
$product = new WP_Query( $args );
while ( $product->have_posts() ) {
$product->the_post();
wc_get_template_part( 'content', 'product' );
}
wp_reset_postdata();
Thanks
Yes, it can be done (2022 update)
If you want to avoid native WP_Query or using shortcodes, this actually can be done using wc_get_products().
You just need to setup and reset postdata within your foreach loop and setup WooCommerce loop properly.
global $post; // Do not forget this!
$args = array(
'limit' => 15,
'category' => array('printers', 'laptop')
);
$products = wc_get_products( $args );
// Set loop properties
wc_set_loop_prop('columns', 5);
// Start custom WC loop
woocommerce_product_loop_start();
foreach( $products as $product ) {
// Setup postdata
$post = get_post( $product->get_id() );
setup_postdata( $post );
// Get template part
wc_get_template_part( 'content', 'product' );
}
// End loop and reset postdata
woocommerce_product_loop_end();
wp_reset_postdata();
Important note: this will only work if queried products are within any HTML element with the woocommerce class (otherwise WooCommerce CSS won't load for your products). In some templates, the woocommerce class is already part of the DOM (e.g. <body> element), but if it isn't, wrap your loop within an element as such:
<div class="woocommerce my-products-loop">
<?php // Your loop goes here ?>
</div>
TIP: You can set various loop properties using wc_set_loop_prop in the "Set loop properties" part of the code

Trouble with caching and 3 wp_query

In my custom theme in WordPress I have created a front-page.php. There I have three WP_Query's. The first one just takes a custom post type.
$args = array (
'post_type' => array( 'frontpage_element' ),
'orderby' => 'rand',
'posts_per_page' => '1',
);
$query = new WP_Query( $args );
if ($query->have_posts()):
while ($query->have_posts() ) : $query->the_post();
// DISPALY A PICTURE
endwhile;
// Reset postdata
wp_reset_postdata();
endif;
The second is the default Loop.
if (have_posts()) :
while (have_posts()) : the_post(); ?>
the_title();
the_content();
endwhile;
// Reset postdata
wp_reset_postdata();
endif;
The third WP_Query shows the first 6 post entries of a category.
$options = get_option('custom_theme_options');
$categories = implode("," , $options['catprojectlayout']);
$atts = shortcode_atts( array(
'paging' => 'projectpage',
'post_type' => 'post',
'posts_per_page' => '6',
'post_status' => 'publish',
'cat' => $categories,
'cache_results' => false
), $atts );
$paging = $atts['paging'];
unset( $atts['paging'] );
if( isset($_GET[$paging]) )
$atts['paged'] = $_GET[$paging];
else
$atts['paged'] = 1;
$custom_query = new WP_Query( $atts );
$pagination_base = add_query_arg( $paging, '%#%' );
if ($custom_query->have_posts()) : while ($custom_query->have_posts()) : $custom_query->the_post();
the_title();
the_content();
endwhile; endif;
echo paginate_links( array(
'type' => '',
'base' => $pagination_base,
'format' => '?'. $paging .'=%#%',
'current' => max( 1, $custom_query->get('paged') ),
'total' => $custom_query->max_num_pages,
'prev_text' => '<div class="prevbtn"></div>',
'next_text' => '<div class="nextbtn"></div>',
'show_all' => true
));
The code works, but I have troubles with caching. When I add a new Post to the defined category, the second WP_Query was not updated (I think because of browser caching).
I think I have the code done like is defined in WP Codex.
It should be work like this: When I add a new post in the defined category, a User browse to the front-page, the site must be reloaded from server (because in the third WP_Query there is a new entry).
it is ulikely to be browser caching as browsers tend to store style sheets and images page content is normally re-interpreted each time the page is loaded incase it has changed.
It is more likely to be either cashing on the server or another 3rd party service such as Cloud flare which store the page appearance for a period of time to save regenerating the same wedge of dynamic page controls over and over.
WP_Engine hosting has it's own caching that can be cleared through the installs dash board, Cloud flare allows cache to be cleared per URL and plugins... well these are all different, check if there are any plugins that control caching and either turn them off whilst you are making a change or clear their cache.

wp_insert_post not working from within wp-admin

I have a Wordpress problem I am trying to figure out; trying to create a wp-admin script that creates a new wp post…
Here is the code:
$my_post = array(
'post_title' => 'My post Gman99',
'post_content' => 'This is my post.',
'post_status' => 'draft',
'post_author' => 1,
'post_category' => array(8,39)
);
$post_id = wp_insert_post( $my_post );
echo $post_id;
And let me stress that this code works fine if I run it on a "front end" page; i just put the code in short code using "short code exec php" plugin and it creates the post no problem and spits out the post id; but when I try to do the same from within wp-admin it fails? dos anyone have any idea why this would be occurring?
here is the code of the php file that runs in wp-admin:
<?php
require_once('./admin.php');
if ( !current_user_can('edit_posts') )
wp_die(__('Cheatin’ uh?'));
require_once('./admin-header.php');
?>
<div class="wrap">
<br/>
<?php
$my_post = array(
'post_title' => 'My post Gman99',
'post_content' => 'This is my post.',
'post_status' => 'draft',
'post_author' => 1,
'post_category' => array(8,39)
);
$post_id = wp_insert_post( $my_post );
echo $post_id;
echo "<br/>";
echo "<h2>You have completed entering your New Slide.</h2>";
echo "<br/>";
?>
</div>
<?php
include('./admin-footer.php');
?>
I figured it out, my own mistake; but thanks so much to Rahil being willing to help…
basically the problem was that I was not calling the file that I thought; and so basically my code to insert the post was not being run when i thought it was; a really rookie mistake...

wordpress post gallery functions does not show the number of posts

hi i have this code i created in content-gallery.php
but when i use printf to show the number of photos within the post does not show it
it must be print
[This Post Gallery Contains 9 Photos.]
but does not work. why?
when my errors?
<?php
$the_images = get_children( array(
'post_parent' => $post->ID, // Pass the ID of a post or Page to get its children. Pass 0 to get attachments without parent. Pass null to get any child regardless of parent.
'post_mime_type'=> 'image', // A full or partial mime-type, e.g. image, video, video/mp4, which is matched against a post's post_mime_type field.
'post_type' => 'attachment',
'orderby' => 'menu_order',
'order' => 'ASC',
'numberposts' => 999
));
if ( !empty($the_images) ) {
$the_total_images = count($the_images);
$the_images = array_slice($the_images, 0, 10); // prin_r form 0 to 10 images
?>
<p><strong>
<?php printf (_n('This Post Gallery Contains %s Photo.', 'This Post Gallery Contains %s Photos.', $the_total_images, 'the-bootstrap'), $the_total_images); ?>
</strong></p>
<?php } ?>
Try using sprintf() instead of printf().
Also, make sure to not have any spaces when using functions. spaces are alright once your within the brackets, but have the space in printf () is bad practice and most of the time errors or doesn't work.
You're checking if the_images is not empty. If it is empty then $the_total_images is never set.
I don't understand your usage of array_slice either. Surely it would be more efficient to only get 10 posts.
Here's how I'd do it:
<?php
global $post;
$the_images = get_posts( array(
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_type' => 'attachment',
'post_status' => 'any',
'orderby' => 'menu_order',
'order' => 'ASC',
'posts_per_page' => -1,
) );
$the_total_images = ( $the_images ) ? count( $the_images ) : 0;
$image_count_text = sprintf( _n( 'This Post Gallery Contains %s Photo.', 'This Post Gallery Contains %s Photos.', $the_total_images, 'the-bootstrap' ), $the_total_images); ?>
<p><strong><?php echo $image_count_text; ?></strong></p>
$the_total_images is no longer dependent on the outcome of get_posts(). I've left it loading all image attachments but I think a better solution could be found if you're only going to use 10.

How do i show wordpress attachments from current post?

So with my blog i have a photo attachment page but it only shows to photo's at a time, and those two photo's are used as the navigation and i hate that.
I want the attachment page to show all the photo's that goes along with the rest of that set.
Here is the current code
<div id="nav-images" class="navigation clearfix">
<div class="nav-next"><?php next_image_link() ?></div>
<div class="nav-previous"><?php previous_image_link() ?></div>
How do i change that to show all the post attachments?
To clarify, this doesn't work anymore - at least with version 3.5.2. I used this instead;
$attachments = get_children(
array(
'post_type' => 'attachment',
'post_parent' => get_the_ID()
)
);
foreach ($attachments as $attachment) {
// ...
}
Only resurrecting an old thread because this one ranks quite highly for this search term.
When you're on a page or post, you can get all of its attachments with the following:
global $post; // refers to the post or parent being displayed
$attachements = query_posts(
array(
'post_type' => 'attachment', // only get "attachment" type posts
'post_parent' => $post->ID, // only get attachments for current post/page
'posts_per_page' => -1 // get all attachments
)
);
foreach($attachements as $attachment){
// Do something exceedingly fancy
}
Since you're currently on an attachment page, you can get all the other attachments using the $post->post_parent value:
global $post; // refers to the attachement object
$attachements = query_posts(
array (
'post_type' => 'attachment', // only get "attachment" type posts
'post_parent' => $post->post_parent, // attachments on the same page or post
'posts_per_page' => -1 // get all attachments
)
);
To then display the attachment images, you can use the wp_get_attachment_image_src function. The attachment's ID will be available in each iteration of your foreach loop as $attachement->ID (if you use the same naming convention as my first example).
Since WordPress 3.6.0 you can also use get_attached_media.
$media = get_attached_media( 'image', $post->ID );
if(! empty($media)){
foreach($media as $media_id => $media_file){
$thumbnail = wp_get_attachment_image_src ( $media_id, 'thumbnail' );
$full = wp_get_attachment_url( $media_id );
echo '<img src="'.$thumbnail[0].'" alt="'.$media_file->post_title.'" />';
}
}

Resources