How to check if the post exists before wp_insert_post to avoid duplication?
The code below works if I remove the 'if' statement (post_exists()) and just keep reinserting posts producing multiple duplications. I wrote the if-statement with post_exists() just to start implementing the logic of checking but the moment I add the if statement, something breaks and the list below doesn't even get printed.
$body = wp_remote_retrieve_body( $request );
$data = json_decode(utf8ize($body), true);
$data_events = $data['events'];
if( ! empty( $data_events ) ) {
echo '<ul>';
foreach( $data_events as $event ) {
// the if statement below seems to break things ie. no li below printed.
if ( post_exists( $event['name'] ) == 0 ) {
echo 'exists';
} else {
echo 'doesnt exist';
}
echo '<li>';
echo $event['id'];
echo '' . $event['name'] . '';
echo '</li>';
$new_post = array(
'post_title' => $event['name'],
'post_content' => 'description',
'post_status' => 'publish',
'post_author' => '2',
'post_type' => 'post',
'post_category' => array(1),
'meta_input' => array(
'hq_id' => $event['id'],
)
);
//wp_insert_post($new_post); // commented out while testing the if statement.
}
echo '</ul>';
}
?>
Edit: please see the $data_events array:
https://pastebin.com/rC60iNyJ
The post_exists() function is not normally available on the front end. Instead of including another file you can use get_page_by_title to find a post by it's title. Just test for a null value to check if it doesn't exist.
Replace
if ( post_exists( $event['name'] ) == 0 ) {
with
if ( get_page_by_title( $event['name'] ) == null ) {
Try this code. you need to include this file.
because post_exists function will work on admin page not in frontend.
if ( ! is_admin() ) {
require_once( ABSPATH . 'wp-admin/includes/post.php' );
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode(utf8ize($body), true);
$data_events = $data['events'];
if( ! empty( $data_events ) ) {
echo '<ul>';
foreach( $data_events as $event ) {
// the if statement below seems to break things ie. no li below printed.
if ( post_exists( $event['name'] ) == 0 ) {
echo 'doesnt exist';
} else {
echo 'exists';
}
echo '<li>';
echo $event['id'];
echo '' . $event['name'] . '';
echo '</li>';
$new_post = array(
'post_title' => $event['name'],
'post_content' => 'description',
'post_status' => 'publish',
'post_author' => '2',
'post_type' => 'post',
'post_category' => array(1),
'meta_input' => array(
'hq_id' => $event['id'],
)
);
//wp_insert_post($new_post); // commented out while testing the if statement.
}
echo '</ul>';
}
Related
I am trying to create a shortcode to connect to an API but there is a problem with the shortcode. I know that it is because a function is inside a functinon but I can't figure out how to fix. I tried something that didn't work.
// Add Shortcode
function api_test() {
function execute_request( $args ) {
global $base_url;
$target_url = add_query_arg( $args, $base_url );
$data = wp_remote_get( $target_url );
echo '<pre><code>';
print_r( $data['body'] );
echo '<code></pre>';
}
if ( ! current_user_can( 'manage_options' ) ) die();
// API variables, please override
$base_url = 'https://website.com';
$email = 'email#gmail.com';
$product_id = '1146';
$license_key = '0g96b29x5v27fmfnmbr4hxaflky';
$instance = '';
$request = ( isset( $_GET['request'] ) ) ? $_GET['request'] : '';
$links = array(
'check' => 'Check request',
'activation' => 'Activation request',
'deactivation' => 'Deactivation',
'version_check' => 'Version Check',
);
foreach ( $links as $key => $value ) {
echo '' . $value . ' | ';
}
// Valid check request
if ( $request == 'check' ) {
$args = array(
'wc-api' => 'serial-numbers-api',
'request' => 'check',
'email' => $email,
'serial_key' => $license_key,
'product_id' => $product_id
);
echo '<br>';
echo '<br>';
echo '<b>Valid check request:</b><br />';
//execute_request( $args );
$this->execute_request($args);
}
}
add_shortcode( 'api-test', 'api_test' );
Just create execute_request() outside of shortcode.
function execute_request( $args ) {
global $base_url;
$target_url = add_query_arg( $args, $base_url );
$data = wp_remote_get( $target_url );
echo '<pre><code>';
print_r( $data['body'] );
echo '<code></pre>';
}
function api_test() {
if ( ! current_user_can( 'manage_options' ) ) die();
// API variables, please override
$base_url = 'https://website.com';
$email = 'email#gmail.com';
$product_id = '1146';
$license_key = '0g96b29x5v27fmfnmbr4hxaflky';
$instance = '';
$request = ( isset( $_GET['request'] ) ) ? $_GET['request'] : '';
$links = array(
'check' => 'Check request',
'activation' => 'Activation request',
'deactivation' => 'Deactivation',
'version_check' => 'Version Check',
);
foreach ( $links as $key => $value ) {
echo '' . $value . ' | ';
}
// Valid check request
if ( $request == 'check' ) {
$args = array(
'wc-api' => 'serial-numbers-api',
'request' => 'check',
'email' => $email,
'serial_key' => $license_key,
'product_id' => $product_id
);
echo '<br>';
echo '<br>';
echo '<b>Valid check request:</b><br />';
//execute_request( $args );
execute_request($args);
}
}
add_shortcode( 'api-test', 'api_test' );
I use the search result and I GET
$s = $_GET['s'];
Which gives: "mario"
Now there is a category named Mario Bianchi under a main category called Persone
When I GET $s I need to get all posts within that category, I tried the following but I get nothing
$terms = get_terms( 'category', array(
'name__like' => $s,
'hide_empty' => true // Optional
) );
if ( count($terms) > 0 ){
echo '<ul>';
foreach ( $terms as $term ) {
echo '<li>' . esc_html( $term->name ) . '</li>';
}
echo '</ul>';
}
Yet I need the actual post attached, not the category itself
get_terms does just that, it get the terms for your query. What you'll want is WP_Query with a tax_query. You've already got the categories you want to return the posts for, so it shouldn't be too difficult
$terms = get_terms( array(
'taxonomy' => 'category',
'name__like' => $s,
'hide_empty' => true // Optional
) );
$term_ids = array();
if ( ! empty( $terms ) ) {
foreach( $terms as $term ) {
$term_ids[] = $term->term_id;
}
$args = array(
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => 'category',
'terms' => $term_ids,
),
),
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
echo '<ul>';
while ( $query->have_posts() ) {
$query->the_post();
echo '<li>' . esc_html( get_the_title() ) . '</li>';
}
echo '</ul>';
}
wp_reset_postdata();
}
I'm using this code...
function include_post_types() {
$post_types = get_post_types( array (
'show_ui' => true
),
'objects' );
$return = '';
foreach ( $post_types as $post_type ) {
$my_sitemap_options = get_option( 'my_sitemap_settings' );
$post_type_name = $post_type->name;
if ($my_sitemap_options['post_types'] && in_array($post_type_name, $my_sitemap_options['post_types'])) {
$the_excluded = $post_type_name;
$return .= "'" . $the_excluded . "', ";
}
}
return $return;
}
... to return a list of custom post types that I have selected from an options page. This works fine, and if I do this...
echo included_post_types();
...I see this...
'clothes', 'shoes', 'jackets',
...which is what I excpected.
But the problem is when I try to use included_post_types() in a loop to only show posts with those post types, like this:
$sitemap_post_args = array(
'post_type' => array(included_post_types()),
'posts_per_page' => -1,
'orderby' =>'post_type',
'order' =>'asc'
);
$loop = new WP_Query($sitemap_post_args);
global $post_type;
global $post;
echo '<ul>';
$last_post_type = '';
while($loop->have_posts()): $loop->the_post();
$current_post_type = $post->post_type;
$current_post_type_object = get_post_type_object( $current_post_type );
if($current_post_type != $last_post_type) echo "<br /><li><strong>" . $current_post_type_object->labels->name . "</strong></li>";?>
<li><?php echo get_the_title(); ?></li>
<?php echo "\n";
$last_post_type = $current_post_type;
endwhile;
wp_reset_query();
echo '</ul>';
It simply doesn't display anything on my page, but it doesn't throw an error either.
I'm almost certain the problem is this line:
'post_type' => array(included_post_types()),
I even tried it like this...
'post_type' => included_post_types(),
...but it did not work.
If I try this...
'post_type' => array('clothes', 'shoes', 'jackets', ),
...it works, but I need to be able to use the function name.
Any suggestions would be helpful.
please replace below code with yours. It should be help.
function include_post_types() {
$post_types = get_post_types( array (
'show_ui' => true
),
'objects' );
$return = array();
foreach ( $post_types as $post_type ) {
$my_sitemap_options = get_option( 'my_sitemap_settings' );
$post_type_name = $post_type->name;
if ($my_sitemap_options['post_types'] && in_array($post_type_name, $my_sitemap_options['post_types'])) {
$the_excluded = $post_type_name;
$return[] = $the_excluded;
}
}
return $return;
}
and also replace below code that show posts
$post_type_list = include_post_types();
$sitemap_post_args = array(
'post_type' => $post_type_list,
'posts_per_page' => -1,
'orderby' =>'post_type',
'order' =>'asc'
);
I have a script that displays users who have published on my site.... Im wondering how I can set the limit that is shown to 10.. I'm new to PHP.. Would I be able to use a foreach to achieve this?
<?php
// Display the widget title
if ( $title ) {
echo $before_title . $title . $after_title;
}
$args = array(
'role' => $role,
'orderyby' => 'post_count',
'order' => 'DESC'
);
$user_ids = get_users($args);
foreach ($user_ids as $user_id) {
if ($postcount) {
if(count_user_posts($user_id->ID)>0) {
echo '<a class="cuda-gravatar" href="'.get_author_posts_url($user_id->ID).'" title="'.$user_id->display_name.'">';
echo get_avatar($user_id->ID, $size);
echo '</a>';
} else {
}
} else {
echo '<a class="cuda-gravatar" href="'.get_author_posts_url($user_id->ID).'" title="'.$user_id->display_name.'">';
echo get_avatar($user_id->ID, $size);
echo '</a>';
}
}
You may try this (number):
$args = array(
'role' => $role,
'orderyby' => 'post_count',
'order' => 'DESC',
'number' => 10 // <-- add this
);
You may also use offset, read more on Codex about get users().
The classic way would be to set a limit to your sql query
$args = array(
...
'posts_per_page' => 10
);
or your can add a counter
foreach ($user_ids as $user_id) {
$i++
...
if($i==10){break;}
}
I've been reading a lot of how to customize excerpt function in WordPress but I have no idea how to proceed with this.
The theme that I am using already have 4 pre-customized excerpt functions and the one that I will show here is closest to my desired but still needs to improve.
My question is how to stop erasing HTML formating from my content (line breaks, paragraphs, font variants, etc)?
add_shortcode('display_news_s5', 'be_display_posts_shortcode5');
function be_display_posts_shortcode5($atts) {
// Pull in shortcode attributes and set defaults
extract( shortcode_atts( array(
'post_type' => 'post',
'post_parent' => false,
'id' => false,
'tag' => '',
'category' => '',
'offset' => 0,
'posts_per_page' => '1',
'order' => 'DESC',
'orderby' => 'date',
'include_date' => false,
'include_excerpt' => false,
'excerpt_l' => 8,
'taxonomy' => false,
'tax_term' => true,
'tax_operator' => 'IN'
), $atts ) );
// Set up initial query for post
$args = array(
'post_type' => explode( ',', $post_type ),
'tag' => $tag,
'category_name' => $category,
'p' => $id,
'posts_per_page' => $posts_per_page,
'order' => $order,
'orderby' => $orderby,
'offset' => $offset
);
// If Post IDs
if( $id ) {
$posts_in = explode( ',', $id );
$args['post__in'] = $posts_in;
}
// If taxonomy attributes, create a taxonomy query
if ( !empty( $taxonomy ) && !empty( $tax_term ) ) {
// Term string to array
$tax_term = explode( ', ', $tax_term );
// Validate operator
if( !in_array( $tax_operator, array( 'IN', 'NOT IN', 'AND' ) ) )
$tax_operator = 'IN';
$tax_args = array(
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $tax_term,
'operator' => $tax_operator
)
)
);
$args = array_merge( $args, $tax_args );
}
// If post parent attribute, set up parent
if( $post_parent ) {
if( 'current' == $post_parent ) {
global $post;
$post_parent = $post->ID;
}
$args['post_parent'] = $post_parent;
}
$listing = new WP_Query( apply_filters( 'display_posts_shortcode_args', $args, $atts ) );
$count = 0;
if ( !$listing->have_posts() )
return apply_filters ('display_posts_shortcode_no_results', false );
$inner = '';
while ( $listing->have_posts() ): $listing->the_post(); global $post;
$count++;
if( $count == 1 ){
$style = ' news-main-post';
} else {
$style = ' news-list-posts';
}
$title = '<div class="news-listing-title"><a class="title" href="'. get_permalink() .'">'. get_the_title() .'</a></div>';
if ($include_date == 'true') $date = ' <div class="news-listing-meta"><span class="news-listing-date">'. get_the_date() . '</span><span class="news-listing-comment">('. get_comments_number() .')</span></div>';
else $date = '';
if ($include_excerpt == 'true') $excerpt = '<span>' .excerpt($excerpt_l) . '</span>';
else $excerpt = '';
$output = '<div class="news-listing' . $style . '"><div class="news-listing-item">'. $title . $excerpt . $date . '</div></div>';
$inner .= apply_filters( 'display_posts_shortcode_output', $output, $atts, $title, $excerpt, $date );
endwhile; wp_reset_query();
$open = apply_filters( 'display_posts_shortcode_wrapper_open', '<div class="news-listing-wrapper-s3">' );
$close = apply_filters( 'display_posts_shortcode_wrapper_close', '<div class="clear"></div></div>' );
$return = $open . $inner . $close;
return $return;
}
Have a look here: LINK looks like its doing what you want to acchieve.