My shop is WooCommerce. I'm currently trying to make it so that if a product in my shop is using the placeholder, it is automatically set to draft. I have also made it so this code finds the products without images, it will apply the image in $src mostly just for testing so I can see that this part is working at least. I'm not the most comfortable with PHP and the code below is a combination of other peoples suggestions and methods I have found!
I have removed the actual link below for data protection and added in a fake one. Any help is appreciated.
add_filter('woocommerce_placeholder_img_src', 'wp_kama_woocommerce_placeholder_img_src_filter');
function wp_kama_woocommerce_placeholder_img_src_filter($src) {
$src = 'https://domain/location/image.png';
$placeholder_image = get_option('woocommerce_placeholder_image', 0);
$args = array('post_type' => 'product', 'posts_per_page' => - 1, 'post_status' => 'publish', 'fields' => 'ids', 'meta_query' => array(array('ID' => $post->ID, 'post_status' => 'publish',)),);
if (!empty($placeholder_image)) {
if (is_numeric($placeholder_image)) {
$image = wp_get_attachment_image_src($placeholder_image, $size);
if (!empty($image[0])) {
$src = $image[0];
$loop_arg = new WP_Query($args);
$loop_ids = $loop_arg->posts;
foreach ($loop_ids as $loop => $loop_id) {
wp_update_post(array('ID' => $loop_id, 'post_status' => 'publish'));
wp_reset_query();
}
}
} else {
$src = $placeholder_image;
$loop_arg = new WP_Query($args);
$loop_ids = $loop_arg->posts;
foreach ($loop_ids as $loop => $loop_id) {
wp_update_post(array('ID' => $loop_id, 'post_status' => 'draft'));
wp_reset_query();
}
}
}
return $src;
}
return apply_filters('woocommerce_placeholder_img_src', $src);
UPDATE: If anyone needs it, I got this code working. This code will check my products and if it has an image, it will publish it, if not, it will draft.
$args = array('post_type' => 'product', 'posts_per_page' => - 1,
'post_status' => array('publish', 'draft', 'trash'), 'fields' => 'ids');
$loop_arg = new WP_Query($args);
$loop_ids = $loop_arg->posts;
foreach ($loop_ids as $loop => $loop_id) {
wp_update_post(array('ID' => $loop_id));
$placeholder_image = get_the_post_thumbnail($loop_id);
if (!$placeholder_image) {
wp_update_post(array('ID' => $loop_id, 'post_status' => 'draft'));
} else {
wp_update_post(array('ID' => $loop_id, 'post_status' => 'publish'));
}
wp_reset_query();
}
Related
When i try to add one post to db using wp_insert_post() in db added two posts:
Ajax request:
/wp-admin/admin-ajax.php?action=getchats&chat_type=all-chat&last_msg=110&add_msg=true&chat_message=helloworlds
action for this:
add_action( 'wp_ajax_getchats', 'getchats');
function getchats(){
if (!isset($_GET['last_msg'])||(!is_numeric($_GET['last_msg'])||(!isset($_GET['chat_type'])))){
die(json_encode(array('error' => 'no_latest')));
}
$cat_id = get_cat_ID($_GET['chat_type']); //the categories name
if ((isset($_GET['add_msg']))&&(isset($_GET['chat_message']))){
$user_id = get_current_user_id();
$description = $_GET['chat_message'];
$title = $description;
if (strlen($title)>20){
$title = mb_substr($title, 0, 20, 'UTF-8');
}
$my_post = array(
'post_content' => $description,
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'chatmsg',
'post_author' => $user_id,
'post_category' => array($cat_id)
);
wp_insert_post($my_post);
}
$args=array(
'numberposts' => 3,
'orderby' => 'ID',
'category' => $cat_id,
'post_type' => 'chatmsg',
'post_status' => 'publish',
);
$messages = [];
$posts = get_posts($args);
die(json_encode($posts));
foreach( $posts as $post ){
if ($post->ID > $_GET['last_msg']){
$row = array(
'id' => $post->ID,
'message'=>$post->post_content,
'author'=>$post->post_author,
'date'=>$post->post_date,
);
$message[] = $row;
}
}
die(json_encode(array('error' => 'ok', 'messages'=> $messages)));
}
Why am i using only one wp_insert_post but receive two post?
UPD: Need use wp_doing_ajax for it. Thanks for answer Maxim Sarandi.
if( wp_doing_ajax() ) {
add_action('wp_ajax_getchats', 'getchats');
function getchats()
{
//some code
}
}
Maybe this or this might help you.
And can i give you a few recommendation to your code style?
First - use $_POST for similar queries.
Second - stop use die(wp_send_json()). Inside wp_send_json already present die(); Just use wp_send_json_error() for error response or wp_send_json_success(); or wp_send_json()
Third - use nonces and check_ajax_referer();
Fourth - stop cloning not needed brackets.
I have this code
function display_categoria($args) {
$query = new WP_Query(array(
'post_type' => 'job_listing',
'post_status' => 'publish',
'posts_per_page' => 5
));
while ($query->have_posts()) {
echo $query->the_post();
$id=get_the_id();
echo $query1=get_permalink();
}
wp_reset_query();
}
add_shortcode( 'este', 'display_categoria' );
in theory i can solve it placing in the loop
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
but many entries not have a thumbnail (featured images), Can understand?
This should retrieve the url of the first image for each post. Insert it after the "$id=get_the_id();" line
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'posts_per_page' => -1,
'post_status' => null,
'post_parent' => $id
);
$images = get_posts( $args );
if ( $images ) {
$first_image_id = $images[0];
//do something with the image
wp_reset_postdata();
}
I am fairly new to Wordpress and I am trying to make a function that loads images under a media category. The media category has a slug that I want to pass into the function. If there is an easier way to do this please let me know. Below is my code so far:
Functions.php
function get_image_by_slug($slug) {
$query_images_args = array(
'post_type' => 'attachment',
'post_mime_type' =>'image',
'post_status' => 'inherit',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'attachment_category',
'field' => 'slug',
'terms' => $slug,
),
),
);
$query_images = new WP_Query( $query_images_args );
$images = array();
foreach ( $query_images->posts as $image) {
$images[]= $image->guid;
}
return $images;
}
function display_image_by_slug() {
$imgs = get_image_by_slug($slug);
$html = '<ul class="list-inline">';
foreach($imgs as $img) {
$html .= '<li><img src="' . $img . '" alt="" /></li>';
}
$html .= '</ul>';
return $html;
}
add_filter('display_slugs','display_image_by_slug');
In page
<?php apply_filter('display slugs', 'test_slug');?>
An attachment of image or file is just a post with the post_status = inherit and the post_type = attachment and it is saved into the wp_post & wp_postmeta , so can be queried with WP_Query or get_posts.
Note: The slug (post_name) is unique per post type.
You have to pass your slug in the query by replacing YOUR-SLUG in this place. &name=YOUR-SLUG
$_head = get_posts('post_type=attachment&name=YOUR-SLUG&posts_per_page=1&post_status=inherit');
$header = $_head ? array_pop($_head) : null;
$header_url = $header ? wp_get_attachment_url($header->ID) : '';
Another Method you can build your own custom function with the help that i have provided below.
function get_attachment_url_by_slug( $slug ) {
$args = array(
'post_type' => 'attachment',
'name' => sanitize_title($slug),
'posts_per_page' => 1,
'post_status' => 'inherit',
);
$_head = get_posts( $args );
$header = $_head ? array_pop($_head) : null;
return $header ? wp_get_attachment_url($header->ID) : '';
and then you can call using this function.
$header_url = get_attachment_url_by_slug('YOUR-SLUG');
So after looking around the Wordpress docs and understanding Naresh's answer I was able to come up with my own answer. Here it is...
$id = 'YOUR SLUG';
$args = array(
'post_type' => 'attachment',
'post_status' => 'any',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'media_category', // your taxonomy
'field' => 'slug',
'terms' => $id // term id (id of the media category)
)
)
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>'. wp_get_attachment_image( get_the_ID() );
if(empty_content(get_the_content())){
echo '<p>' . get_the_excerpt() . '</p></li>';
} else {
echo '<p>'.get_the_excerpt().'</p></li>';
}
}
} else {
// no attachments found
}
wp_reset_postdata();
I have been struggling with this for some time now and would really appreciate some help!
I am trying to populate html5 audio player with 2 codexes in Wordpress media library.
I am using the wp function get_posts and created one filter for post_mime_types 'ogg'. I have set the parameters for post_mime_type in get_posts's $args. Now I want to loop over and sort them into the audio player list as $mp3 and $ogg.
$ogg = wp_get_attachment_url( $audio_attachment->post_mime_type="application/ogg" );
... in the code below but not outputting anything:
<?php
$query_audio_args = array(
'post_type' => 'attachment',
'post_mime_type' =>'application/ogg,audio',
'post_status' => 'inherit',
'posts_per_page' => -1,
);
$audio_attachments = get_posts($query_audio_args);
foreach ( $audio_attachments as $audio_attachment ) {
// Trying to sort them into $ogg, $aif and $mp3
$ogg = wp_get_attachment_url( $audio_attachment->ID);
$mp3 = wp_get_attachment_url( $audio_attachment-ID);
$tracks[] = '{
title:"'.$audio_attachment->post_title.'",
mp3:"'.$mp3.'",
oga:"'.$ogg.'",
aif:"'.$aif.'"
}';
$alltracks = implode(',',$tracks);
}
?>
Edit:
I also tried this, with the intention of creating a multiple array, but got stuck accessing the values:
<?php
$query_audio_args = array(
'post_type' => 'attachment',
'post_mime_type' =>'application/ogg',
'post_status' => 'inherit',
'posts_per_page' => -1,
);
$audio_attachments = get_posts($query_audio_args);
$ogg = array();
foreach ( $audio_attachments as $uk => $uv ) {
$ogg[] = $uv->guid;
}
$query_audio_args1 = array(
'post_type' => 'attachment',
'post_mime_type' =>'audio',
'post_status' => 'inherit',
'posts_per_page' => -1,
);
$audio_attachments1 = get_posts($query_audio_args1);
$mp3 = array();
foreach ( $audio_attachments1 as $ak => $av ) {
$mp3[] = $av->guid;
}
$audio = array(
$ogg,
$mp3
);
print_r($audio);
foreach($audio as $k =>$v)
$tracks[] = '{
title:"'.$uv->post_title.'",
mp3:"'.$mp3->guid.'",
oga:"'.$uv->guid.'",
aif:"'.$aifv->guid.'"
}';
$alltracks = implode(',',$tracks);
?>
This question is about tidying up code and better management of said code butI'm a complete novice when it comes to PHP so would appreciate a little help.
I have this code:
<?php
$thumb_id = get_post_thumbnail_id(get_the_ID()); // gets the post thumbnail ID
$args = array(
'order' => 'ASC',
'orderby' => 'rand',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => 1,
'exclude' => $thumb_id
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
echo wp_get_attachment_image($attachment->ID, 'full', false);
}
}
?>
What it does isn't important for reference, the above code gets random images from a Wordpress post randomly generates one of them in a DIV. I want this functionality across many templates but I don't want to cram my PHP files with it as my files will get messy and inefficiently large.
2 questions.
Do I need to change the code above in order to put it within functions.php?
How can I reference the above code (that will be within my functions.php) using a short one liner that I can reuse across many different templates?
You may like to try putting the snippet in to a function, inside functions.php, and passing it a few parameters, allowing the usage to be more flexible.
Untested, but this takes an array of options, and overwrites the default values (e.g for changing the order or orderby etc on a per-use basis). As an optional parameter you can pass a post_id, in case you want to query a post that isn't the current one.
It also returns an array of rather than outputs them directly, which can be seen as the preferred way of working with functions.
// functions.php
function get_random_post_image($options=array(), $post_id=NULL) {
if($post_id != NULL) :
$thumb_id = get_post_thumbnail_id($post_id);
else :
$thumb_id = get_post_thumbnail_id(get_the_ID());
endif;
$default_args = array(
'order' => 'ASC',
'orderby' => 'rand',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => 1,
'exclude' => $thumb_id
);
// merge custom options
$args = array_merge($default_args, $options);
$attachments = get_posts($args);
if ($attachments) {
$images = array();
foreach ($attachments as $attachment) {
$images[] = wp_get_attachment_image($attachment->ID, 'full', false);
}
return $images;
}
return false; // or, return default image/placeholder
}
// and within your template/posts:
if(function_exists('get_random_post_image')) :
$images = get_random_post_image(array('order'=>'DESC')); // overwrite `ASC`
if($images) :
foreach($images as $img) {
echo '<div class="post-img"> ' . $img . '</div>';
}
else :
echo 'No images!';
endif;
endif;
not perfect; but you could extend it easily enough.
1. You need to get out the <?php and ?> if you already put your code inside those tags
example functions.php:
<?php
blah blah
....
// your code here
$thumb_id = get_post_thumbnail_id(get_the_ID()); // gets the post thumbnail ID
$args = array(
'order' => 'ASC',
'orderby' => 'rand',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => 1,
'exclude' => $thumb_id
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
echo wp_get_attachment_image($attachment->ID, 'full', false);
}
}
// be careful, only one "?>" in the file, no nested "<?php ?>" blocks
?>
2. Use include(), include_once(), require() or require_once() and save your function in another file, so you can reference that file.
random_img.php
<?php
$thumb_id = get_post_thumbnail_id(get_the_ID()); // gets the post thumbnail ID
$args = array(
'order' => 'ASC',
'orderby' => 'rand',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => 1,
'exclude' => $thumb_id
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
echo wp_get_attachment_image($attachment->ID, 'full', false);
}
}
?>
functions.php
<?php
blah blah
....
include ("random_img.php")
?>