I'm using the Posts 2 Posts plugin. I have many different post types and many different connection types.
I create all those relationships like so
function register_post_type_connections() {
$connection_post_types = array('person', 'nonprofit', 'business', 'article', 'event', 'structure', 'government');
foreach($connection_post_types as $post_type){
p2p_register_connection_type( array(
'name' => $post_type .'_to_structure',
'from' => $post_type, // use $my_post_types if you didn't define $temp_array
'to' => 'structure',
'reciprocal' => false,
'duplicate_connections' => true,
'sortable' => true,
));
}
// Foreach repeated for each $connection_post_types
}
add_action( 'p2p_init', 'register_post_type_connections' );
The foreach loops is repeated 7 total times in this function to get every possible combination. I've tested the result and it works correctly
Many connections are made and attached to individual post pags. I want to show a list of all these connections made.
I get a complete list of all the connection types like this
function get_all_connection_types() {
$connection_types = array();
$connection_post_types = array('person', 'nonprofit', 'business', 'article', 'event', 'structure', 'government');
foreach($connection_post_types as $post_type){
$connection_types[] = $post_type .'_to_person';
$connection_types[] = $post_type .'_to_nonprofit';
$connection_types[] = $post_type .'_to_business';
$connection_types[] = $post_type .'_to_article';
$connection_types[] = $post_type .'_to_event';
$connection_types[] = $post_type .'_to_structure';
$connection_types[] = $post_type .'_to_government';
}
return $connection_types;
}
Then I run my loop
$post_types = array('person', 'nonprofit', 'business', 'article', 'event', 'structure', 'timeline', 'government');
$connection_types = get_all_connection_types();
$connected = new WP_Query( array(
'connected_type' => $connection_types,
'post_type' => $post_types,
'connected_items' => 'any',
'connected_direction' => 'to',
'posts_per_page' => 20,
'orderby' => 'meta_value',
'connected_orderby' => 'date',
'connected_order' => 'desc'
) );
echo '<ul>';
if ( $connected->have_posts() ) {
while ( $connected->have_posts() ) :
$connected->the_post();
Here are my connections from the database
My loops is only returning person_to_person connections. So I tested by changing connected_type to..
$connection_types = array('person_to_structure', 'person_to_person');
This gives me the person_to_structure connections but not the person_to_person.
Why?
You need to pass "connected_direction" as array with exact length of that "connected_type" has for this change this code on your index file.
$post_types = array('person', 'nonprofit', 'business', 'article', 'event', 'structure', 'timeline', 'government');
$connection_types = get_all_connection_types();
$direction_array = array();
for($i=0;$i<count($connection_types);$i++) {
$direction_array[$i] = 'from'; // if you want then you can send the from as well;
}
$connected = new WP_Query( array(
'connected_type' => $connection_types,
'post_type' => $post_types,
'connected_items' => 'any',
'connected_direction' => $direction_array,
'posts_per_page' => 20,
'orderby' => 'meta_value',
'connected_orderby' => 'date',
'connected_order' => 'desc'
) );
This will work.
Related
This code does not set the object terms. Please help me sort out the issue. The code results in the posts list and doesn't set the terms.
I have checked the below data.
The query results in the list of post.
calculation part in the loop results in the value (lesser or greater than 0)
function set_expired_job_categories() {
global $post;
$current_time = time();
$taxonomy = 'current-status';
$job_expired_id = 368;
$job_ongoing_id = 367;
// Set our query arguments
$args = array(
'fields' => 'ids', // Only get post ID's to improve performance
'post_type' => 'job', // Post type
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array(
'taxonomy' => 'current-status',
'field' => 'slug',
'terms' => array( 'ongoing' ),
),
);
$job_expiration_query = new WP_Query( $args );
// Check if we have posts to delete, if not, return false
if( $job_expiration_query->have_posts() ){
while( $job_expiration_query->have_posts() ){
$job_expiration_query->the_post();
$postid = get_the_ID();
$expire_timestamp = rwmb_meta( 'deadline_date' );
if ( $expire_timestamp ) {
$seconds_between = ( (int)$expire_timestamp - (int)$current_time );
if ( $seconds_between <= 0 ) {
wp_set_object_terms( $postid, (int)$job_expired_id, $taxonomy, true );
wp_remove_object_terms( $postid, (int)$job_ongoing_id, $taxonomy );
}
}
}wp_reset_postdata();
}
}
add_action( 'set_job_categories', 'set_expired_job_categories', 20, 2 );
As it is in the functions file, I need to set the global $wp_taxonomies to populate the taxonomies data initially. Also, instead of using the tag_ID, I have revised with the slug. These two changes helped to work out the code. The revised code is below for reference.
Thank you all for your efforts.
function set_expired_job_categories() {
global $post;
global $wp_taxonomies;
$current_time = time();
$taxonomy = 'current-status';
$job_expired_id = 'expired';
$job_ongoing_id = 'ongoing';
// Set our query arguments
$args = array(
'fields' => 'ids', // Only get post ID's to improve performance
'post_type' => 'job', // Post type
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array(
'taxonomy' => 'current-status',
'field' => 'slug',
'terms' => array( 'ongoing' ),
),
);
$job_expiration_query = new WP_Query( $args );
// Check if we have posts to set categories, if not, return false
if( $job_expiration_query->have_posts() ){
while( $job_expiration_query->have_posts() ){
$job_expiration_query->the_post();
$postid = get_the_ID();
$expire_timestamp = rwmb_meta( 'deadline_date' );
if ( $expire_timestamp ) {
$seconds_between = ( (int)$expire_timestamp - (int)$current_time );
if ( $seconds_between >= 0 ) {
}else {
wp_set_object_terms( $postid, (int)$job_expired_id, $taxonomy, true );
wp_remove_object_terms( $postid, (int)$job_ongoing_id, $taxonomy );
}
}
}
wp_reset_postdata();
}
}
// hook it to low priority value, due to CPT and Taxonomies
add_action( 'set_job_categories', 'set_expired_job_categories', 20, 2 );
Reference: https://wordpress.org/support/topic/wp_set_object_terms-in-loop-is-not-work-in-taxonomy-cpt/
I've implemented an infinite scroll and in search results upon ordering by price or any custom value it doesn't work.
Here inside my enqueued script:-
isset($_GET['orderby'])?$ga_order_by = $_GET['orderby']: $ga_order_by = '';//grabbing the orderby value
if( gettype($result) == 'object') {
$ga_wp_query = new \WP_Query([ 'post_type'=> ['product_variation', 'product'], 'post__in' => $includes, 'orderby' => ['post__in',$ga_order_by], 'order' => 'ASC' ]);//so i'm ordering by search results and dynamically grabbed value.
} else {
$ga_wp_query = new \WP_Query([ 'post_type'=> 'product', 'post__in' => $includes, 'orderby' => ['post__in',$ga_order_by], 'order' => 'ASC']);
}
$args['ga_search_posts'] = json_encode($ga_wp_query->query_vars);
Inside my ajax handling function call upon search:-
$search_query = json_decode( stripslashes( $_POST['search_posts'] ), true );//this is the $args['ga_search_posts'] i'm posting via my javascript
$search_query['post_status'] = 'publish';
$search_query['posts_per_page'] = get_option('posts_per_page');
$search_query['paged'] = $_POST['page'] + 1;
wc_set_loop_prop( 'total', $_POST['search_count'] );
add_filter( 'woocommerce_get_price_html', 'labtag_show_price' );
ob_start();
query_posts( $search_query);
if ( have_posts() ) {//product loop
if ( wc_get_loop_prop( 'total' ) ) {
while ( have_posts() ) {
the_post();
wc_get_template_part( 'content', 'product' );
}
}
}
$data = ob_get_clean();
die($data);
exit;
This works except if I try to order by any parameter say price etc. Can't 'orderby' => ['post__in',$ga_order_by] declared like an array?If not should I be passing all my posts ids to the ajax handler iterate them and sort them (if this is the case, how to handle my custom order_by params)?
https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
So, with WordPress' OrderBy, you have a couple of different options.
If you want both parameters to be sorted in the same direction of ASC or DESC, then the argument anticipates a single string, with the parameters separated by a space.
Multiple 'orderby' values Display pages ordered by 'title' and
'menu_order'. (title is dominant):
$args = array(
'post_type' => 'page',
'orderby' => 'title menu_order',
'order' => 'ASC',
);
$query = new WP_Query( $args );
You use an array when you are sorting each parameter differently:
Multiple 'orderby' values using an array
> Display pages ordered by 'title' and 'menu_order' with different sort
> orders (ASC/DESC) (available since Version 4.0):
$args = array(
'orderby' => array( 'title' => 'DESC', 'menu_order' => 'ASC' )
);
$query = new WP_Query( $args );
In your case, since you are using a variable, consider building the string and then using this within your arguments array, i.e.:
//start with a space, then .= to concatenate the $_GET parameter with the space if it's set, or clear the string if it's not.
$ga_order_by = " ";
isset($_GET['orderby'])?$ga_order_by .= $_GET['orderby']: $ga_order_by = '';
//grabbing the orderby value and building our complete string.
$orderBy = 'post__in'.$ga_order_by;
if (gettype($result) == 'object') {
$ga_wp_query = new \WP_Query([ 'post_type'=> ['product_variation', 'product'], 'post__in' => $includes, 'orderby' => $orderBy , 'order' => 'ASC' ]);//so i'm ordering by search results and dynamically grabbed value.
} else {
$ga_wp_query = new \WP_Query([ 'post_type'=> 'product', 'post__in' => $includes, 'orderby' => $orderBy, 'order' => 'ASC']);
}
I developed a plugin that reads a csv file in order to create 4 different custom taxonomies (Categories) and 1 custom post type (Post) using PHP and WordPress.
On the Initial import the execution time is less than 6 seconds, however the second time execution takes more than 1 minute in order to reset and re-upload the data.
The issue that I found is on the resetAllPosts function (see code)
public function resetAllPosts() {
$query = new WP_Query( array(
'post_type' => 'psp',
'post_status' => 'publish',
'posts_per_page' => 100
) );
// remove all taxonomies will take too long..
// delete all custom taxonomies terms
$terms_payment = get_terms( 'payment', array( 'fields' => 'ids', 'hide_empty' => false ) );
$terms_country = get_terms( 'country', array( 'fields' => 'ids', 'hide_empty' => false ) );
$terms_currency = get_terms( 'currency', array( 'fields' => 'ids', 'hide_empty' => false ) );
$terms_provider = get_terms( 'provider', array( 'fields' => 'ids', 'hide_empty' => false ) );
foreach ( $terms_payment as $value ) {
wp_delete_term( $value, 'payment' );
}
foreach ( $terms_country as $value ) {
wp_delete_term( $value, 'country' );
}
foreach ( $terms_currency as $value ) {
wp_delete_term( $value, 'currency' );
}
foreach ( $terms_provider as $value ) {
wp_delete_term( $value, 'provider' );
}
while ( $query->have_posts() ) {
$query->the_post();
$post_id = get_the_ID();
// remove the relation between the post and the taxonomies
//wp_delete_object_term_relationships(get_the_ID(),array("provider","payment","currency","country"));
// Remove the feature image from Media gallery
//$post_thumbnail_id = get_post_thumbnail_id( $post_id );
//wp_delete_attachment( $post_thumbnail_id, true );
// delete the post
wp_delete_post( $post_id, "true" );
}
echo "Reset of all data success..";
}
I would like to know the best/fastest way to delete all terms data.
I'm clearly not doing this right. Any help would be greatly appreciated. Essentially i am pulling nearby zip codes and city names to a search that is being done. i then want to use WP_Query to pull the WordPress post types matching those zip codes and city names. I'm not super familiar with WordPress, so it is highly likely i'm way off base on how to do this:
$url = "http://www.zipcodeapi.com/rest/OeAp3k78myEhBy0oqSlQSlUWOt6N7TjW8Tlbdtkz1YRCwS1WKmNDIHzwbFjizCeI/radius.json/" . $searchbox . "/100/km";
$response = file_get_contents($url);
$json = json_decode($response);
$post_type = 'location';
$citysearcharray = array();
$zipsearcharray = array();
$searcharray = array();
foreach($json->zip_codes as $nearbyzip)
{
$citysearcharray[] = array(
'key' => 'city',
'value' => $nearbyzip->city,
'compare' => '='
);
$zipsearcharray[] = array(
'key' => 'zip_code',
'value' => $nearbyzip->zip_code,
'compare' => '='
);
}
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'caller_get_posts'=> 1,
'posts_per_page' => 10,
'meta_query' => array(
'relation' => 'OR',
$citysearcharray,
$zipsearcharray));
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
$count=0;
echo '<ul class="location">';
while ($my_query->have_posts()) : $my_query->the_post();
...
Amy i putting the $args together correctly?
TIA
In your foreach, instead of adding new full values to your arrays
$zipsearcharray
and
$citysearcharray
have the value key as an array so:
'value' => array(array of cities)
then change
compare => 'IN'
Hey everyone,
I have a post type called `index`, and i'm trying to build a form for users to insert posts from the frontend.
i created a page and a template for it with a form and an ajax function which insert the content to the DB using `wp_insert_post`. the function works generally, i can see the new posts added to the wp_post db in phpmyadmin. the problem is that i can't see the new posts in the admin panel. the post are counted (i can see the number goes up everytime i try the form), but not shown.
this is the functions.php ajax code (some $_get vars are to be used for meta data inserting):
add_action('wp_ajax_addtoindex', 'addtoindex');
add_action('wp_ajax_nopriv_addtoindex', 'addtoindex');
function addtoindex(){
$title = $_GET["title"];
$slug = sanitize_title_with_dashes($title,'','save');
$group = $_GET["group"];
$inst = $_GET["inst"];
$location = $_GET["location"];
$address = $_GET["address"];
$content = $_GET["content"];
$website = $_GET["website"];
$year = $_GET["year"];
$educ = $_GET["educ"];
$aud = $_GET["aud"];
$teaching = $_GET["teaching"];
$teachers = $_GET["teachers"];
$contact1 = $_GET["contact1"];
$email1 = $_GET["email1"];
$phone1 = $_GET["phone1"];
$contact2 = $_GET["contact2"];
$email2 = $_GET["email2"];
$phone2 = $_GET["phone2"];
$user = get_user_by("login",$authorid);
$authorid = $user->ID;
// Check if the group exists
$group_term = term_exists( $group, 'group', 0 );
// Create group if it doesn't exist
if ( !$group_term ) {
$group_term = wp_insert_term( $group, 'group', array( 'parent' => 0 ) );
}
// Check if the inst exists
$inst_term = term_exists( $inst, 'inst', 0 );
// Create inst if it doesn't exist
if ( !$inst_term ) {
$inst_term = wp_insert_term( $inst, 'inst', array( 'parent' => 0 ) );
}
// Check if the location exists
$location_term = term_exists( $location, 'location', 0 );
// Create location if it doesn't exist
if ( !$location_term ) {
$location_term = wp_insert_term( $location, 'location', array( 'parent' => 0 ) );
}
$custom_tax = array(
'group' => $group_term,
'inst' => $group_inst,
'location' => $group_location
);
//Post Properties
$new_post = array(
'post_title' => $title,
'post_name' => $slug,
'post_content' => $content,
'post_status' => 'pending',
'post_type' => 'index',
'post_author' => $authorid,
'comment_status' => 'closed',
'ping_status' => 'closed',
'tax_input' => $custom_tax
);
//save the new post
if ( post_type_exists( 'index' ) ) {
$pid = wp_insert_post($new_post, true);
echo 'good';
}
else{
echo "bad";
}
// Reset Post Data
wp_reset_postdata();
exit;
}
and this is the index post type code:
function post_type_index() {
register_post_type( 'index',
array(
'label' => __('Index'),
'labels' => array('name' => 'אינדקס האנתרופוסופיה','singular_name' => __('פריט לאינדקס','ohav'),'edit_item' => __('עריכת פריט אינדקס','ohav'),'add_new' => __('הוספת פריט לאינדקס','ohav'),'add_new_item' => __('הוספת פריט לאינדקס','ohav'),'all_items' => __('לכל פריטי האינדקס','ohav')),
'public' => true,
//'publicly_queryable' => true,
//'query_var' => true,
//'capability_type' => 'post',
'has_archive' => true,
'show_ui' => true,
'show_in_nav_menus' => true,
'rewrite' =>array(
'slug' => __('index','ohav'),
'with_front' => true
),
'hierarchical' => true,
'supports' => array(
'title',
'boxplace',
'editor',
'thumbnail'
)
)
);
}
add_action('init', 'post_type_index');
okay i found it!
the problem was i already had a pre_get_posts hook that changes the order of the index archive according to the post meta.
add_action( 'pre_get_posts', 'change_order_for_index' );
function change_order_for_index( $query ) {
if ( is_post_type_archive('index') ) {
$query->set( 'meta_key', '_index_featured' );
$query->set( 'orderby', 'meta_value' );
}
}
i added && !is_admin() to the if and it turned okay.
thank you Arif, your answer helped me find it.
you can add an action hook 'pre_get_posts' to include/exclude your custom post type to/from the admin post list or any for any other listing like archives.
add_filter( 'pre_get_posts', 'include_custom_type_index' );
function include_custom_type_index( $query ) {
$query->set( 'post_type', array(
'post', 'index'
));
return $query;
}