Schedule wordpress posts on uploading images - php

I have the following code that works perfect on creating posts from images on uploading from wordpress dashboard by media uploads, but I need to schedule this posts at a specific interval (30 minutes one new post):
<?php
$autopost_controler = get_theme_mod( 'auto_onoff' );
if( $autopost_controler != '' ) {
switch ( $autopost_controler ) {
case 'on':
add_action('add_attachment', 'auto_post_on_image_upload');
function auto_post_on_image_upload($attachId)
{
$attachment = get_post($attachId);
$image = wp_get_attachment_image_src( $attachId, 'large');
$image_tag = '<p><img src="'.$image[0].'" /></p>';
$cidargs = array('category_name' => get_theme_mod('cat_1'));
$cid = array(get_category_by_slug($cidargs['category_name'])->term_id);
$theoriginaltitle = $attachment->post_title;
$onetitle = str_replace("-"," ",$theoriginaltitle);
$thetitlef = str_replace("_"," ",$onetitle);
$thetitle = ucwords(strtolower($thetitlef));
$content = '<strong>'. $thetitle .' </strong> is a funny photo posted in <strong>'.$cidargs['category_name'].'</strong> category. If you like <strong>'. $thetitle .'</strong> funny image, please share it with your friends.';
$alltags = $thetitle;
$createtags = explode(" ", $alltags);
$postData = array(
'post_title' => $thetitle,
'post_type' => 'post',
'post_content' => $content,
'post_category' => $cid,
'tags_input' => $createtags,
'post_status' => 'publish'
);
$post_id = wp_insert_post($postData);
// attach media to post
wp_update_post(array(
'ID' => $attachId,
'post_parent' => $post_id
));
set_post_thumbnail($post_id, $attachId);
return $attachId;
}
break;
case 'off':
break;
}
}

Related

Check exists post title

I created plugin for get post title via API on submit. I used simple api request for getting data after via wp_insert_post() function add to DB. But i want check every time on submit to exists title. If there is a new post title then add to the database if not then it will report that 'There are no new posts'
plugin.php
if(isset($_POST['enable'])) {
$url='api/url';
$result = file_get_contents($url);
$resultData = json_decode($result);
foreach ($resultData as $job) {
$post_exists = get_page_by_title( $job->JobTitle, OBJECT, 'post');
if ( post_exists) {
$data = array (
'post_type' => 'post',
'post_title' => $job->JobTitle,
'post_status' => 'publish',
'post_author' => $user_ID
);
$post_id = wp_insert_post( $data );
}
}
echo "Done!";
}
Try this code.
if( isset( $_POST['enable'] ) ) {
$url = 'api/url';
$result = file_get_contents( $url );
$resultData = json_decode( $result );
foreach ($resultData as $job) {
$post_title = sanitize_title( $job->JobTitle );
$post_id = post_exists( $post_title );
if( !$post_id ){
$data = array(
'post_type' => 'post',
'post_title' => $post_title,
'post_status' => 'publish',
'post_author' => $user_ID,
);
$post_id = wp_insert_post( $data );
}else{
//post title exist
}
}
}
You should try this,
This code will return an array of all posts that match the title.
global $wpdb;
$query = $wpdb->prepare('SELECT ID FROM ' . $wpdb->posts . ' WHERE post_title = "'.$post_title.'" AND post_status="publish"');
$post_exists = $wpdb->get_results( $query );

Wordpress: Display image attachments from child pages of a specific page

I am trying to display all image attachments on the child pages of a specific parent page, i.e. all the pictures on Pages 10, 11 and 12.
Projects (Page ID: 5)
- Project 1 (Page ID: 10)
- Project 2 (Page ID: 11)
- Project 3 (Page ID: 12)
This is what I have so far, and it works to display all images on the site:
<?php
$args = array(
'post_parent' => 0,
'post_type' => 'attachment',
'numberposts' => -1
);
$images = get_children( $args );
if ( empty($images) ) {
// no attachments here
} else {
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, 'full' );
}
}
?>
However, if I add the post parent ID (5), nothing comes up:
<?php
$args = array(
'post_parent' => 5,
'post_type' => 'attachment',
'numberposts' => -1
);
$images = get_children( $args );
if ( empty($images) ) {
// no attachments here
} else {
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, 'full' );
}
}
?>
Any suggestions would be really helpful!
I think get_children() return objects from a single parent post or all (passing 0 as value).
You may try a nested foreach to get all post children first, then query attachment page by page. Here is an untested sample, but it gives you an idea:
<?php
$subpages_args = array(
'post_parent' => 5,
'post_type' => 'page',
'numberposts' => -1
);
$sub_pages = get_children( $subpages_args );
foreach( $sub_pages as $subpage_id => $sub_page) {
$args = array(
'post_parent' => subpage_id,
'post_type' => 'attachment',
'numberposts' => -1
);
$images = get_children( $args );
if ( empty($images) ) {
// no attachments here
} else {
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, 'full' );
}
}
}
?>
Good luck :)
Here is an SQL Query based solution. Copy following function in your theme's functions.php
function get_children_page_attachments($parent_id) {
global $wpdb;
// just a precautionary typecast and check
$parent_id = intval( $parent_id );
if( empty($parent_id) ) return [];
$query = "SELECT ID FROM {$wpdb->posts} P WHERE post_type='attachment' AND P.post_parent IN (SELECT ID FROM {$wpdb->posts} WHERE post_parent={$parent_id} AND post_type='page' )";
return $wpdb->get_results($query, 'ARRAY_A');
}
Once you have above function in your functions.php, then you can use it like this:
// for example the parent page id is 16
$image_ids = get_children_page_attachments(16);
foreach($image_ids as $image_id) {
$image = wp_get_attachment_image($image_id['ID'], 'full');
}

wp returns "wrong" image ID

well,
Code dosent make mistakes so i have something i dont see here...
I have following code on wp page:
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_parent' => $pages->ID
);
$images = get_posts($args);
$attachment_id = $images[0]->ID;
$i = wp_get_attachment_image_src($attachment_id, $size);
$p = array_values($i)[0];
if (has_post_thumbnail()) {
the_post_thumbnail($size);
} else {
} ?>
It, works, in a way.
it will return a image url and i can use it to show images on page, anyhow the ID it return seems to be somewhat random.
I have the right ID for page to look for images in $pages
i would need to return first image of that page.
I would assume, array[0] would be first image of page, but obviously it is not since it returns very strange pictures from another page, which has nothing to do with this page.
I'm not sure but seems you are doing it wrong. :)
Why can't you use
echo get_the_post_thumbnail( $post_id, 'thumbnail', array( 'class' => 'alignleft' ) )
or
get_the_post_thumbnail_url( int|WP_Post $post = null, string|array $size = 'post-thumbnail' )
or
get_post_thumbnail_id( $post_id );
Please Try :
global $post;
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_parent' => $pages->ID
);
$images = get_posts($args);
$attachment_id = $images[0]->ID;
$i = wp_get_attachment_image_src($attachment_id, $size);
$p = array_values($i)[0];
if (has_post_thumbnail($post->ID )) {
the_post_thumbnail($size);
} else {
}

Get images by a slug in Wordpress

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();

How to create Wordpress posts from external json file?

Here is the code I am using. It creates duplicate post every time I refresh. Also, how can I add custom field to my post?
My array looks like this:
[{
"featured":"",
"exclusive":"",
"promo_id":"XXX",
"offer_id":"1",
"title" : "Super Cars"
}]
My php code:
<?php
$json = "url";
$response = file_get_contents($json);
$mydecode = json_decode($response);
for ($i = 10; $i < 15; $i++) {
$title = str_replace("&", "&", $mydecode[$i]->title);
$id = $mydecode[$i]->offer_id;
$link = $mydecode[$i]->link;
if( $id === "x" ) {
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'draft',
'post_author' => 1,
'post_type' => 'coupon'
);
$post_id = wp_insert_post($new_post);
}
}
?>
The code successfully inserts posts but duplicate every time I refresh.
If anyone can contribute a bit, it would be great!
Update your code to following,
<?php
$json = "http://tools.vcommission.com/api/coupons.php?apikey=xxxxxxxxxx";
$response = file_get_contents($json);
$mydecode = json_decode($response);
for ($i = 0; $i < 15; $i++) {
$title = str_replace("&", "&", $mydecode[$i]->coupon_title);
$description = str_replace("&", "&", $mydecode[$i]->coupon_description);
$store_name = $mydecode[$i]->offer_name;
$coupon_type = $mydecode[$i]->coupon_type;
$coupon_code = $mydecode[$i]->coupon_code;
$link = $mydecode[$i]->link;
$expiry_date = $mydecode[$i]->coupon_expiry;
if( $coupon_type === "Coupon" ) {
// Check if already exists
$get_page = get_page_by_title( $title );
if ($get_page == NULL){
// Insert post
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'draft',
'post_author' => 1,
'post_type' => 'coupon'
);
// Insert post
$post_id = wp_insert_post($new_post);
// Insert post meta if available
add_post_meta( $post_id, 'meta_key', 'meta_value' );
// Uncomment to check if meta key is added
// $get_meta_value = get_post_meta( $post_id, 'meta_key', true );
// echo "<pre>";
// print_r($get_meta_value);
}
}else{
// Update meta value
update_post_meta($get_page->ID, 'my_key', 'meta_value');
// Uncomment to check if meta key is added
// $get_meta_value = get_post_meta( $get_page->ID, 'meta_key', true );
// echo "<pre>";
// print_r($get_meta_value);
}
}
?>
I hope this helps.

Categories