how to get relation field with condition - php

When we want to get some relation field we do
$pod = pods( 'pod_name', get_the_id() );
$related = $pod->field( 'relationship_field' );
and I get list of results array 1, 2 ...
but I need to get relationship_field where name="some_name". How can I do that?

The following will retrieve the related field named relationship_field if the related post has a title equal to some_name:
$pod = pods('pod_name', get_the_ID());
$params = array(
'WHERE' => "relationship_field.post_title = 'some_name'",
);
$related = $pod->find($params);

You're example was right, but with a minor tweak this will be more useful as an example:
// get the pod record based on current post ID
$pod = pods( 'pod_name', get_the_ID() );
$params = array(
// be sure to sanitize the value going in, if it's dynamic
'where' => 'relationship_field.post_title = "Some title"'
);
// find records that match $params
$pod->find( $params );
// loop through records found
while ( $pod->fetch() ) {
// do something with $pod->field( 'field_name' )
// or $pod->display( 'field_name' )
}

Related

wp-job-manager show expired offers at end of list

I'm trying to figure this out with no luck, on the ajax list I want to sort the listings so that expired ones are at the end.
I've tried to use this filter
add_filter ( 'get_job_listings_query_args', 'sort_by_expired' );
function sort_by_expired( $query_args ) {
$today = date("Y-m-d", strtotime($date));
$query_args['orderby'] = 'meta_value_num';
$query_args['order'] = 'DESC';
// $query_args['meta_key'] = '_job_expires';
$query_args['meta_query'][] = array(
array(
'key' => '_job_expires',
// 'value' => date('Y-m-d'),
// 'compare' => '>='
)
);
return $query_args;
}
I've noticed that the code changes the order but not in the way I've would have wanted.
I tried to change different parameters (you can see the quoted out parts) changing:
mata_value_num to meta_value adding removing meta query parameters but with no luck.
From what i can understand you want to sort it by _job_expires ASC for the ones that are not expired and then display expired ones by DESC. this will have to be done in 2 separate queries. you can merge both arrays after that
edit: Merge 2 seperate queries' results as follows
//setup your queries as you already do
$query1 = new WP_Query($args_for_query1);
$query2 = new WP_Query($args_for_query2);
//create new empty query and populate it with the other two
$wp_query = new WP_Query();
$wp_query->posts = array_merge( $query1->posts, $query2->posts );
//populate post_count count for the loop to work correctly
$wp_query->post_count = $query1->post_count + $query2->post_count;
This is how I got it to work
public function depcore_custom_orderby( $query_args ) {
// Use meta_value_num for numeric sorting (if issues with meta_value)
$query_args[ 'orderby' ] = 'meta_value';
$query_args[ 'order' ] = 'DESC';
return $query_args;
}
public function depcore_custom_orderby_query_args( $query_args ) {
$query_args[ 'meta_key' ] = '_job_expires';
return $query_args;
}
Because I'm using the plugin boilerplate the filter call is used in the plugin public part
$this->loader->add_filter( 'job_manager_get_listings_args', $plugin_public, 'depcore_custom_orderby', 99 );
$this->loader->add_filter( 'get_job_listings_query_args', $plugin_public,'depcore_custom_orderby_query_args', 99 );

Wordpress wp_query get result into variables

Currently I'm using get_posts to get the 10 latest posts, but the problem is that I don't get all information. For example I can't access the post category or author.
I would like to use WP_Query with get_the_title(), get_the_post_thumbnail, get_permalink() etc. The results have to be stored into variables.
My setup:
$latest_posts = get_posts( array(
'category_name' => 'Allgemein',
'posts_per_page' => 10,
"orderby" => "date",
"order" => "DESC"
) );
// Post 1 -- Category: Allgemein
if ( isset( $latest_posts[0] ) ) { // array zero-based index.
// $post1_category = $latest_posts[0]->post_category;
$post1_date = $latest_posts[0]->post_date;
$post1_title = $latest_posts[0]->post_title;
// $post1_tags = $latest_posts[0]->post_tags;
$post1_author = $latest_posts[0]->post_author;
$post1_content = $latest_posts[0]->post_content;
$post1_thumbnail = $latest_posts[0]->get_the_post_thumbnail;
}
// Post 2 -- Category: Allgemein
if ( isset( $latest_posts[1] ) ) {
// $post2_category = $latest_posts[1]->post_category;
$post2_date = $latest_posts[1]->post_date;
$post2_title = $latest_posts[1]->post_title;
// $post2_tags = $latest_posts[1]->post_tags;
$post2_author = $latest_posts[1]->post_author;
$post2_content = $latest_posts[1]->post_content;
$post2_thumbnail = $latest_posts[1]->get_the_post_thumbnail;
}
Post3-10
....
And in my index.php:
<div class="title">
<?php echo $post1_title?>
</div>
To get the categories, use the function wp_get_post_categories:
$post1_category = wp_get_post_categories($latest_posts[0]->ID);
To get the tags, use the function wp_get_post_tags:
$post1_tags = wp_get_post_tags($latest_posts[0]->ID);
WordPress has more functions to retrieve the post data using the post ID. Follow:
Get the Title
Get the post thumbnail URL
Your variable $latest_posts[X] is a WP_Post Object, wich contains some data. See the full data list in the WP_Post Reference.

How to filter custom field array through get post meta then write to CSV

I have a code snippet that I use throughout my site, it reads the product IDs from a custom field "menu_listing" and displays content (like image, title, hyperlink, etc.) in an unordered list. I use this in various places on my site (ex. https://eatgoodathome.com/order/menu).
I am trying to get that list of product names to output next to customer order info in my Export Orders to CSV plugin. Here is the code pertaining to "menu_listing".
global $post;
// Date Range Parameters
$today = date("Y-m-d");
$next = date("Y-m-d", strtotime( "$today +2 weeks"));
// Query current menu based on date
$menu_args = array(
'post_type'=>'single_menu',
'posts_per_page' => 1,
'meta_query' => array(
array(
'key' => "delivery_date",
'value' => array( $today, $next ),
'type' => 'date',
'compare' => 'BETWEEN'
),
));
// Display custom field
$menu = new WP_Query( $menu_args );
if ( $menu->have_posts() ) {
while ( $menu->have_posts() ) {
$menu->the_post();
}
// This is the custom field, content looks like this: [{"id":"9115"},{"id":"8256"},{"id":"8539"},{"id":"5586"}]
$current_menu = json_decode( stripcslashes( get_post_field( "menu_listing", $post->id ) ) );
if( $current_menu ){
foreach( $current_menu as $single_block ) {
if( $single_block->id ) {
$dishes = get_post( $single_block->id )->post_title;
}}}}
//Output CSV cells
$row = array( $dishes );
In the state shown above, it loops through all the all the products, and only displays the name for the last one. I tried using implode(), explode(), an additional foreach() — those all seem to be a step in the wrong direction, outputting a blank column. What am I missing?
It looks like you're reassigning the value of $dishes with each iteration which is why you're only seeing the name of the last item. Try doing this instead:
$dishes[] = get_post( $single_block->id )->post_title;
This way, you'll be creating a new index of the $dishes array every iteration instead of reassigning its value. Then you can just assign $row = $dishes.
SOLUTION: The code in my question looped through the array and only gave the last item in the array. My goal was to loop through each key/value pair, convert the value ("id") to title, and have each title populate a column for my csv. My solution involved scrapping the foreach statement, and requesting each array in the loop by its offset, then assigning it a column in the csv file.
//Output for CSV
$output = fopen('php://output', 'w');
if ( $menu->have_posts() ) {
while ( $menu->have_posts() ) {
$menu->the_post();
}
// This is the custom field, content looks like this: [{"id":"9115"},{"id":"8256"},{"id":"8539"},{"id":"5586"}]
$current_menu = json_decode( stripcslashes( get_post_field( "menu_listing", $post->id ) ) );
$dish1 = get_post( $current_menu[0]->id )->post_title;
$dish2 = get_post( $current_menu[1]->id )->post_title;
$dish3 = get_post( $current_menu[2]->id )->post_title;
// Validate for 4th array item, if exists
if( sizeof($current_menu) === 4 ) {
$dish4 = get_post( $current_menu[3]->id )->post_title;
} else {
$dish4 = "";
}
}
//Output CSV cells
$row = array( $dish1, $dish2, $dish3, $dish4 );
fputcsv( $output, $row );

WooCommerce pagination on single product pages - but only inside parent category

I would like to put pagination on each single product page in WooCommerce so that a user can move between products in that category easier than having to go back out to the main category page every time.
I know it's possible to use the standard WordPress pagination links like…
<?php previous_post_link('« %link'); ?>
<?php next_post_link('%link »'); ?>
This works if I want to page through all products, but I only want to page through products that are within the category I'm in. Does anyone know how I can limit this so products outside this category aren't included?
I've tried using the in_same_term parameter as mentioned in the WordPress codex to get the links only showing if the next/prev product is in the same category, but it's returning an integer for some reason. Here's the code I'm using…
<?php next_post_link( '%link', '%title', TRUE, '' ); ?>
This returns nothing at all even though it follows the Codex structure. I've also tried…
<?php next_post_link( '%link %title', TRUE, '' ); ?>
And this is what I'm getting in return…
1 %title
I'm stumped where to go next.
Here is a function that I have recently written that also does the job and is quite flexible
THE IDEA:
You first need to get the current post id, which I get through get_queried_object_id(). The post ID will be used to retrieve:
The post terms the post belongs to with wp_get_post_terms(). To speed things up, only the ID's of the terms will be returned. The first ID will be used (you can modify the code here to decide which term will be used if a post have more than one term) and this will be used to retrieve all the posts which has this certain term
The post ID's of the posts that is directly adjacent to this post to determine and retrieve the next and previous post from this one
All the info above will be used in a tax_query with get_posts to retrieve all the posts that shares the term from the current post. In the function, the default taxonomy is category and the post_type is set to any to get all the posts that has this specific term
Again, to make the code faster and to safe on resources, we only going to get the post ID's as this is all that is needed
Now comes the important parts of the code. We now need to determine the following:
The current position of the current post in the returned array of post ID's from the custom get_posts query. The function used here is array_search
If there is a post before or after this post (next or previous posts, the definitions are the same as for the build in functions next_post_link() and previous_post_link()), get the ID's of these posts
Use the ID's with get_post to retrieve the next and previous post's titles from the current post
Lastly will be to return the links. I have set messages if the current post is either the first or last post in the array and there are no next or previous post. You can decide what you want to do here, and for all that matters, the rest of the code
To make the code even faster and more efficient, I have made use of the Transient API which you can read further on. I have also used the transition_post_status action hook to hook a function to delete these transients whenever the post status of a post change. This includes new posts being published, post being updated and post deleted/undeleted
THE CODE:
Here is the code. This goes into your functions.php
function get_post_link( $taxonomy = 'category', $post_type = [ 'any' ] ) {
$id = get_queried_object_id(); // Get the current post ID
$transient_id = 'post_number_' . md5( $id . $taxonomy . implode( ',', $post_type ) ); //Create a unique transient id
if ( false === ( $links = get_transient( $transient_id ) ) ) {
// Get the terms a post belongs to
$terms = wp_get_post_terms( $id, $taxonomy, array( 'fields' => 'ids' ) );
// Use a tax_query to get all posts from the given term
// Just retrieve the ids to speed up the query
$post_args = [
'post_type' => $post_type,
'fields' => 'ids',
'posts_per_page' => -1,
'tax_query' => [
[
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => $terms[0],
'include_children' => false,
],
],
];
// Get all the posts having the given term from all post types
$q = get_posts( $post_args );
//Get the current post position. Will be used to determine next/previous post
$current_post_position = array_search( $id, $q );
// Get the previous/older post ID
if ( array_key_exists( $current_post_position + 1 , $q ) ) {
$previous = $q[$current_post_position + 1];
}
// Get post title link to the previous post
if( isset( $previous ) ) {
$previous_post = get_post( $previous );
$previous_post_link = get_permalink( $previous );
$previous_title = '' . $previous_post->post_title . '</br>';
}
// Get the next/newer post ID
if ( array_key_exists( $current_post_position - 1 , $q ) ) {
$next = $q[$current_post_position - 1];
}
// Get post title link to the next post
if( isset( $next ) ) {
$next_post = get_post( $next );
$next_post_link = get_permalink( $next );
$next_title = '' . $next_post->post_title . '</br>';?><pre><?php var_dump($next_title); ?></pre><?php
}
// The returned post links
if( isset( $previous_title, $next_title ) ) {
$links = [
'previous_post' => $previous_title,
'next_post' => $next_title,
];
}elseif( !isset( $previous_title ) && $next_title ) {
$links = [
'previous_post' => 'You are currently viewing the newest post',
'next_post' => $next_title,
];
}elseif( $previous_title && !isset( $next_title ) ) {
$links = [
'previous_post' => $previous_title,
'next_post' => 'You are currently viewing the last post',
];
}
set_transient( $transient_id, $links, 7 * DAY_IN_SECONDS );
}
return (object)$links;
}
add_action( 'transition_post_status', function ( $new_status, $old_status, $post )
{
global $wpdb;
$wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient%_post_number_%')" );
$wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient_timeout%_post_number_%')" );
}, 10, 3 );
HOW TO USE:
You can now use the code as follows in you single.php. The default taxonomy is category and post type is any. If your custom taxonomy is called mytax, you can use the code like this
if( function_exists( 'get_post_link' ) ) {
$post_links = get_post_link( 'mytax' );
echo $post_links->previous_post . '</br>' . $post_links->next_post;
}

Gravity forms input values

I'm new in the php world and i'm trying to build something in wordpress by gravity forms.
Basicly for now I just playing around and try to create some codes I can use when I start building. My question is: I have a form 1 where I can enter a name e.g. Football,Baseball,Hockey and it get saved to my data base. Then I have another form with the id 2 where there is a drop down box, here i want those values(names) submitted in form 1 to be dynamically populated. I have been trying to create a code by finding pieces around some websites (you will properly discover I'm mixing everything together) and ended up with this:
add_filter("gform_pre_render", "test_task");
add_filter("gform_admin_pre_render", "test_task");
add_filter('gform_pre_submission_filter', 'test_task');
function test_task($entry, $form){
if($form["id"] != 2)
return $form;
$entry["1"];
$items = array();
$items[] = array("text" => "Choose Sport", "value" => "");
foreach($posts as $post)
$items[] = array("value" => $post->post_title, "text" => $post->post_title);
foreach($form["fields"] as &$field)
if($field["id"] == 2){
$field["choices"] = $items;
}
return $form;
}
Hope someone can show me how it should be done so I can learn to do it in the future.
Sincerely
Lars
I'm afraid the $entry object is not available to the gform_pre_render, gform_pre_submission_filter or gform_admin_pre_render hooks. Give the following a try.
add_filter( 'gform_pre_render', 'populate_sports_choices' );
add_filter( 'gform_pre_validation', 'populate_sports_choices' );
add_filter( 'gform_pre_submission_filter', 'populate_sports_choices' );
add_filter( 'gform_admin_pre_render', 'populate_sports_choices' );
function populate_sports_choices( $form ) {
// only run for form 2
if( $form['id'] != 2 )
return $form;
foreach ( $form['fields'] as &$field ) {
function populate_sports_choices( $form ) {
foreach ( $form['fields'] as &$field ) {
// only populate the field if it is a select and has the designated css class name
if ( $field['type'] != 'select' || strpos( $field['cssClass'], 'populate-sport' ) === false )
continue;
// get form 1 field 4 entry values
$sports = get_entry_field_values( 4, 1 );
// create the $choices array and set the placeholder choice
$choices = array( array( 'text' => 'Select a Sport', 'value' => '' ) );
// loop through each of the sports and add them to the $choices array
foreach ( $sports as $sport ) {
$choices[] = array( 'text' => $sport['value'], 'value' => $sport['value'] );
}
//replace the field choices with the contents of the $choices array
$field['choices'] = $choices;
}
return $form;
}
/**
* Allows you to retrieve an array of field values.
* Requires either the $field object or a field ID and a form ID.
*
* Example: $values = get_entry_field_values( 5, 113 );
*/
function get_entry_field_values( $field_id, $form_id ) {
global $wpdb;
if ( is_array( $field_id ) ) {
$field_id = rgget( 'id', $field_id );
}
$tablename = $wpdb->prefix . 'rg_lead_detail';
$sql = "SELECT value FROM $tablename WHERE form_id = %d AND CAST(field_number as unsigned) = %d";
return $wpdb->get_results( $wpdb->prepare( $sql, $form_id, $field_id ), ARRAY_A );
}
The above is based on examples from the following sources:
http://www.gravityhelp.com/documentation/page/Dynamically_Populating_Drop_Down_Fields
http://www.gravityhelp.com/forums/topic/drop-down-dynamic-population-from-single-line-text
I don't think you need to write any code at all. This is supported by Gravity Forms itself. In the form editor go to settings > confirmations, then choose redirect, enter the page form 2 is on and select Pass Field Data Via Query String then enter name={Name:1} or something similar depending on the name and id of the fields in Form 1. And then in Form 2, go to the field you want to populate and select advanced and dynamically prepopulate and enter what you typed to the left of the =, in this case name.

Categories