I wanted to use the default search functionality using this :
The problem is I've made this table using this line of code
function waiting_list_column_content_callback($column_name, $post_ID) {
$guestID = get_post_meta( $post_ID, 'guest', true );
$user_info = get_userdata( $guestID );
$floorplanID = get_post_meta( $post_ID, 'floorplan', true );
$notes = get_post_meta( $post_ID, 'notes', true );
$waiting_list = wpr_get_waiting_list( $floorplanID );
$list_location = wpr_get_list_location( $post_ID, wpr_get_waiting_list( $floorplanID ) );
if ( $column_name == 'fname' ) {
echo ''.$user_info->first_name.'';
}elseif ( $column_name == 'lname' ) {
echo ''.$user_info->last_name.'';
}elseif( $column_name == 'floorplan' ){
echo get_the_title($floorplanID);
}
elseif( $column_name == 'logs_print' ){
echo 'Print';
}elseif( $column_name == 'list_location' ){
echo $list_location;
}
}
I've tried this and this. It work, but I can only search the user by "id".Since "id" is the only custom_field available to use.
This is the code I'm using to get results by id. "guest" is the "id" of the user. Which I use to display the last name and the first name of the user.
function extend_admin_search( $query ) {
//Extend search for document post type
$post_type = 'wpr_waiting_list';
// Custom fields to search for
$custom_fields = array(
"guest",
);
if( ! is_admin() )
return;
if ( $query->query['post_type'] != $post_type )
return;
$search_term = $query->query_vars['s'];
// Set to empty, otherwise it won't find anything
$query->query_vars['s'] = '';
if ( $search_term != '' ) {
$meta_query = array( 'relation' => 'OR' );
foreach( $custom_fields as $custom_field ) {
array_push( $meta_query, array(
'key' => $custom_field,
'value' => $search_term,
'compare' => 'LIKE'
));
}
$query->set( 'meta_query', $meta_query );
};
}
add_action( 'pre_get_posts', 'extend_admin_search' );
What I've wanted to do was search this custom post type by "first name" or "last name" .
I've tried some sql codes but I'm getting some "headers" error I don't understand.
Related
I'm using the WP Profile Builder plugin. In the frontend user listing I set a default sorting criteria. Works fine! But now I would like to have a second criteria that comes right after the default one.
Lets say first are the "gold" users and behind them the "silver" users.
Right now it looks like this:
*/
function wppb_userlisting_users_loop( $value, $name, $children, $extra_values ){
if( $name == 'users' ){
global $userlisting_args;
global $wpdb;
$userlisting_form_id = $extra_values['userlisting_form_id'];
$userlisting_args = get_post_meta( $userlisting_form_id, 'wppb_ul_page_settings', true );
if( !empty( $userlisting_args[0] ) ){
$paged = (get_query_var('wppb_page')) ? get_query_var('wppb_page') : 1;
if( !is_int( (int)$userlisting_args[0]['number-of-userspage'] ) || (int)$userlisting_args[0]['number-of-userspage'] == 0 )
$userlisting_args[0]['number-of-userspage'] = 5;
// Check if some of the listing parameters have changed
if ( isset( $_REQUEST['setSortingOrder'] ) && sanitize_text_field( $_REQUEST['setSortingOrder'] ) !== '' )
$sorting_order = sanitize_text_field( $_REQUEST['setSortingOrder'] );
else
$sorting_order = $userlisting_args[0]['default-sorting-order'];
/* if we have admin approval on we don't want to show those users in the userlisting so we need to exclude them */
if( wppb_get_admin_approval_option_value() === 'yes' ){
$excluded_ids = array();
$user_statusTaxID = get_term_by( 'name', 'unapproved', 'user_status' );
if( $user_statusTaxID != false ){
$term_taxonomy_id = $user_statusTaxID->term_taxonomy_id;
$results = $wpdb->get_results( $wpdb->prepare( "SELECT wppb_t1.ID FROM $wpdb->users AS wppb_t1 LEFT OUTER JOIN $wpdb->term_relationships AS wppb_t0 ON wppb_t1.ID = wppb_t0.object_id WHERE wppb_t0.term_taxonomy_id = %d", $term_taxonomy_id ) );
foreach ( $results as $result )
array_push( $excluded_ids, $result->ID );
$excluded_ids = implode( ',', $excluded_ids );
}
}
if( !empty($excluded_ids) )
$extra_values['exclude'] .= ','. $excluded_ids;
//set query args
$args = array(
'order' => $sorting_order,
'include' => $extra_values['include'],
'exclude' => $extra_values['exclude'],
'fields' => array( 'ID' )
);
/* get all field options here, we will need it bellow */
global $wppb_manage_fields;
if( !isset( $wppb_manage_fields ) )
$wppb_manage_fields = get_option( 'wppb_manage_fields', 'not_found' );
// Check if some of the listing parameters have changed
if ( isset( $_REQUEST['setSortingCriteria'] ) && sanitize_text_field( $_REQUEST['setSortingCriteria'] ) !== '' )
$sorting_criteria = sanitize_text_field( $_REQUEST['setSortingCriteria'] );
else
$sorting_criteria = $userlisting_args[0]['default-sorting-criteria'];
if( in_array( $sorting_criteria, array( 'login', 'email', 'url', 'registered', 'post_count', 'nicename' ) ) ){
if( $sorting_criteria == 'nicename' )
$args['orderby'] = 'display_name';
}
else{
$args['orderby'] = apply_filters( 'wppb_ul_sorting_type', 'meta_value', $sorting_criteria );
if ($wppb_manage_fields != 'not_found') {
foreach ($wppb_manage_fields as $wppb_field) {
if( $wppb_field['meta-name'] == $sorting_criteria ){
if( $wppb_field['field'] == 'Number' || $wppb_field['field'] == 'Phone' ){
$args['orderby'] = apply_filters( 'wppb_ul_sorting_type', 'meta_value_num', $sorting_criteria );
}
}
}
}
switch( $sorting_criteria ){
case "bio":
$args['meta_key'] = 'description';
break;
case "firstname":
$args['meta_key'] = 'first_name';
break;
case "lastname":
$args['meta_key'] = 'last_name';
break;
case "nickname":
$args['meta_key'] = 'nickname';
break;
case "role":
$args['meta_key'] = $wpdb->get_blog_prefix().'capabilities';
break;
case "RAND()":
break;
default:
$args['meta_key'] = $sorting_criteria;
}
}
/* the relationship between meta query is AND because we need to narrow the result */
$args['meta_query'] = array('relation' => 'AND');
/* we check if we have a meta_value and meta_key in the shortcode and add a meta query */
if( !empty( $extra_values['meta_value'] ) && !empty( $extra_values['meta_key'] ) ){
$args['meta_query'][0] = array( 'relation' => 'AND' ); //insert relation here
$args['meta_query'][0][] = array(
'key' => $extra_values['meta_key'],
'value' => $extra_values['meta_value'],
'compare' => apply_filters( 'wppb_ul_meta_att_in_shortcode_compare', '=', $extra_values )
);
}
Can someone help me out with that? Best regards, Ingo
I already tried to change some parameters and checked what was changing but no luck for me!
We are using Advanced Custom Fields, WP All Export Pro, and WordPress with Woocommerce.
I have an ACF field created for our accountant in users area of WordPress called "traverse_customer_id". This is for her to know what customer this order is for.
I have this ACF field showing in the orders export but the data comes back blank on each export. I think it's because I'm not relating the order with the customer or user ID. I've attempted to use a code snippet from WP All Exports' support without any luck. Could anyone with knowledge help me see what I'm doing wrong?
This is what I have in the "Custom export field" area: (I think this is running the function on each line of the import.)
[sf_helper_meta_query_lookup("traverse_customer_id",{Customer User ID},"user")]
Then I have this below in the Function Editor:
function sf_helper_meta_query_lookup( $meta_key = '', $meta_value = '', $object_type = 'post', $taxonomy = '', $return_field = 'ID', $compare = '=', $custom_args = array() ) {
if ( empty( $object_type ) || empty( $meta_key ) || empty( $meta_value ) ) return;
$func = 'get_posts';
switch ( $object_type ) {
case 'user':
$func = 'get_users';
break;
case 'term':
$func = 'get_terms';
if ( $return_field == 'ID' ) {
$return_field = 'term_id';
}
break;
default:
$func = 'get_posts';
break;
}
if ( ! empty( $custom_args ) ) {
$objects = $func( $custom_args );
if ( ! empty( $objects ) ) {
return $objects[0]->$return_field;
} else {
return false;
}
}
$args = array();
$meta_query = array( array(
'key' => $meta_key,
'value' => $meta_value,
'compare' => $compare
) );
if ( $func == 'get_terms' ) {
$args = array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
'meta_query' => $meta_query
);
} elseif ( $func == 'get_users' ) {
$args = array(
'meta_query' => $meta_query
);
} else {
$args = array(
'post_type' => $object_type,
'meta_query' => $meta_query
);
}
if ( $objects = $func( $args ) ) {
return $objects[0]->$return_field;
} else {
return false;
}
}
Any help would be greatly appreciated!
I am using "Sensei LMS" and "Sensei LMS Certificates" plugins.
Now , to enhance "Sensei LMS Certificates" plugin functionality , I have created a custom meta box and custom fields like this : https://prnt.sc/104s7oy
I am using this action hook sensei_certificates_before_pdf_output to show text in PDF
I have added the following code in my custom plugin :
<?php
add_action( 'sensei_certificates_before_pdf_output', 'action__sensei_certificates_before_pdf_output' , 20, 2 );
function action__sensei_certificates_before_pdf_output( $pdf_certificate, $fpdf ) {
global $woothemes_sensei_certificates;
$show_border = apply_filters( 'woothemes_sensei_certificates_show_border', 0 );
$start_position = 200;
$args = array(
'post_type' => 'certificate',
'meta_key' => 'certificate_hash',
'meta_value' => $pdf_certificate->hash,
);
$query = new WP_Query( $args );
$certificate_id = 0;
if ( $query->have_posts() ) {
$query->the_post();
$certificate_id = $query->posts[0]->ID;
}
wp_reset_query();
if ( 0 < intval( $certificate_id ) ) {
$user_id = get_post_meta( $certificate_id, 'learner_id', true );
$student = get_userdata( $user_id );
$student_name = $student->display_name;
$fname = $student->first_name;
$lname = $student->last_name;
if ( '' != $fname && '' != $lname ) {
$student_name = $fname . ' ' . $lname;
}
$course_id = get_post_meta( $certificate_id, 'course_id', true );
$course_title = get_post_field('post_title', $course_id);
$course_end = Sensei_Utils::sensei_check_for_activity(
array(
'post_id' => intval( $course_id ),
'user_id' => intval( $user_id ),
'type' => 'sensei_course_status',
),
true
);
$course_end_date = $course_end->comment_date;
$date = Woothemes_Sensei_Certificates_Utils::get_certificate_formatted_date( $course_end_date );
if ( isset( $woothemes_sensei_certificates->certificate_template_fields['certificate_custom_message']['text'] ) && '' != $woothemes_sensei_certificates->certificate_template_fields['certificate_custom_message']['text'] ) {
$certificate_custom_message = $woothemes_sensei_certificates->certificate_template_fields['certificate_custom_message']['text'];
$certificate_custom_message .= str_replace( array( '{{learner}}', '{{course_title}}', '{{completion_date}}', '{{course_place}}' ), array( $student_name, $course_title, $date, get_bloginfo( 'name' ) ), $certificate_custom_message );
}
$output_fields = array(
'certificate_custom_message' => 'textarea_field',
);
foreach ( $output_fields as $meta_key => $function_name ) {
if ( isset( $woothemes_sensei_certificates->certificate_template_fields[ $meta_key ]['position']['x1'] ) ) {
$font_settings = $woothemes_sensei_certificates->get_certificate_font_settings( $meta_key );
call_user_func_array( array( $pdf_certificate, $function_name ), array( $fpdf, $meta_key, $show_border, array( $woothemes_sensei_certificates->certificate_template_fields[ $meta_key ]['position']['x1'], $woothemes_sensei_certificates->certificate_template_fields[ $meta_key ]['position']['y1'], $woothemes_sensei_certificates->certificate_template_fields[ $meta_key ]['position']['width'], $woothemes_sensei_certificates->certificate_template_fields[ $meta_key ]['position']['height'] ), $font_settings ) );
}
}
} else {
wp_die( esc_html__( 'The certificate you are searching for does not exist.', '' ), esc_html__( 'Certificate Error', '' ) );
}
}
but this is how text showing inside PDF : https://prnt.sc/104sg3v
expected result is "Hello Test hii" instead of "certificate_custom_message"
How do I fix this ?
I have a meta box associated with a custom post type. The meta box allows the user to select multiple options from a dropdown and then saves it in the form of the serialized array into the database. If the user selects only one option the meta_value is stored as an integer but if a user selects multiple options then it is saved in the form of a serialized array.
Below are the functions that display and save my meta box
function av_add_meta_box() {
$post_types = array( 'advertisements' );
foreach ( $post_types as $post_type ) {
add_meta_box(
'avd_screen_meta_box', // Unique ID of meta box
'Set Screen', // Title of meta box
'av_display_meta_box', // Callback function
$post_type // Post type
);
}
}
add_action( 'add_meta_boxes', 'av_add_meta_box' );
// display meta box
function av_display_meta_box( $post ) {
$value = get_post_meta( $post->ID, '_av_meta_key', true );
if ( isset( $values['av-meta-box'] ) ) {
$value = esc_attr( $values['ued-av-box'][0] );
}
wp_nonce_field( basename( __FILE__ ), 'av_meta_box_nonce' );
//echo "<pre>"; print_r($value) ; echo "</pre>";
?>
<select id="av-meta-box" type="text" name="av-meta-box[]" multiple="multiple">
<option value="">Select Screen</option>
<?php $screens = json_decode(apply_filters("av_load_screens", "all"));
foreach ($screens as $screen) {
$location_name = json_decode(apply_filters("av_load_locations", $screen->location));
$selected = "";
if(gettype($value) == "array"){
$selected = (in_array($screen->id, $value))?"selected":"";
} else{
$selected = ($screen->id == $value)?"selected":"";
} ?>
<option <?php echo $selected; ?> value="<?php echo $screen->id; ?>"><?php echo $screen->screen_name." - ".$location_name[0]->location_name." (".$location_name[0]->pin.") "; ?></option><?php
} ?>
</select>
<?php
}
// save meta box
function av_save_meta_box( $post_id ) {
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = false;
if ( isset( $_POST[ 'av_meta_box_nonce' ] ) ) {
if ( wp_verify_nonce( $_POST[ 'av_meta_box_nonce' ], basename( __FILE__ ) ) ) {
$is_valid_nonce = true;
}
}
if ( $is_autosave || $is_revision || !$is_valid_nonce ) return;
if ( array_key_exists( 'av-meta-box', $_POST ) ) {
update_post_meta(
$post_id, // Post ID
'_av_meta_key', // Meta key
array_map( 'strip_tags', $_POST[ 'av-meta-box' ])// Meta value
);
}
}
add_action( 'save_post', 'av_save_meta_box' );
And Below are the arguments what I'm passing to my WP_Query
$args = array(
'post_type' => 'advertisements',
'meta_query' => array (
'key' => '_av_meta_key',
'value' => 6,
'compare' => 'IN'
)
);
The above WP_Query returns all post with having meta value 6(integer). But what if the meta_value is stored in a serialized array like a:3:{i:0;s:1:"6";i:1;s:1:"7";i:2;s:1:"8";}
In my case, the
post_id:20, meta_key:_av_meta_key and meta_value:a:3:{i:0;s:1:"6";i:1;s:1:"7";i:2;s:1:"8";}
I want my WP_Query to return the post with id 20 either the meta_value is 6 or 7 or 8.
I'd suggest saving the (multiple) values into multiple rows in the database to avoid the problem from the beginning. WordPress supports saving multiple values with the same key for a custom field.
You can rewrite the code that saves value to:
if ( array_key_exists( 'av-meta-box', $_POST ) ) {
delete_post_meta( $post_id, '_av_meta_key' );
$values = array_map( 'absint', $_POST[ 'av-meta-box' ] );
foreach ( $values as $value ) {
add_post_meta( $post_id, '_av_meta_key', $value, false );
}
}
This way, you can write your query without worrying about serialize data. And getting values from the database is simple as:
$values = get_post_meta( $post_id, '_av_meta_key', false );
PS: I'd suggest using a custom fields plugin to avoid writing repetitive code. It also helps you to solve this problem as I suggested above quickly.
It is difficult to get the correct result using WP_Query with serialised data. You can try using the LIKE keyword instead of IN.
Alternatively you can use a custom $wpdb query to get what you are looking for.
global $wpdb;
$posts = $wpdb->get_results(
$wpdb->prepare(
"
SELECT *
FROM $wpdb->postmeta
LEFT JOIN $wpdb->posts as post
ON post.id = post_id
WHERE post.post_type = %s
AND meta_key = %s
AND meta_value LIKE %s
",
'advertisements',
'_av_meta_key',
':"6";'
)
);
// Check if anything was found
if( $posts !== NULL ) {
foreach($posts as $post_info) {
// $post_info contains all post info as object
echo $post_info->post_title;
}
}
You can change the part where it is :"6"; to the value you are looking for. It would make the search better if you wrap the number in :"{number}";" as this is how it is serialised in your example which would make it more of a exact match
Update: Setting meta key for each screen id
function av_add_meta_box() {
$post_types = array( 'advertisements' );
foreach ( $post_types as $post_type ) {
add_meta_box(
'avd_screen_meta_box', // Unique ID of meta box
'Set Screen', // Title of meta box
'av_display_meta_box', // Callback function
$post_type // Post type
);
}
}
add_action( 'add_meta_boxes', 'av_add_meta_box' );
// display meta box
function av_display_meta_box( $post ) {
$value = get_post_meta( $post->ID, '_av_meta_key', true );
if ( isset( $values['av-meta-box'] ) ) {
$value = esc_attr( $values['ued-av-box'][0] );
}
wp_nonce_field( basename( __FILE__ ), 'av_meta_box_nonce' );
//echo "<pre>"; print_r($value) ; echo "</pre>";
?>
<select id="av-meta-box" type="text" name="av-meta-box[]" multiple="multiple">
<option value="">Select Screen</option>
<?php $screens = json_decode(apply_filters("av_load_screens", "all"));
foreach ($screens as $screen) {
$location_name = json_decode(apply_filters("av_load_locations", $screen->location));
$selected = "";
if(gettype($value) == "array"){
$selected = (in_array($screen->id, $value))?"selected":"";
} else{
$selected = ($screen->id == $value)?"selected":"";
} ?>
<option <?php echo $selected; ?> value="<?php echo $screen->id; ?>"><?php echo $screen->screen_name." - ".$location_name[0]->location_name." (".$location_name[0]->pin.") "; ?></option><?php
} ?>
</select>
<?php
}
// save meta box
function av_save_meta_box( $post_id ) {
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$screens = json_decode(apply_filters("av_load_screens", "all"));
$is_valid_nonce = false;
if ( isset( $_POST[ 'av_meta_box_nonce' ] ) ) {
if ( wp_verify_nonce( $_POST[ 'av_meta_box_nonce' ], basename( __FILE__ ) ) ) {
$is_valid_nonce = true;
}
}
if ( $is_autosave || $is_revision || !$is_valid_nonce ) return;
if ( array_key_exists( 'av-meta-box', $_POST ) ) {
$selected_screens = array_map( 'absint', $_POST[ 'av-meta-box' ] );
foreach($screens as $screen) {
update_post_meta(
$post_id,
'_av_meta_key_' . $screen->id,
in_array( $screen->id, $selected_screens ) ? 'yes' : 'no'
);
}
}
}
add_action( 'save_post', 'av_save_meta_box' );
Then when you want to use WP_Query you can build an array to search for all keys and set the relation to OR.
$meta_query = [
'relation' => 'OR',
];
$screens = json_decode(apply_filters("av_load_screens", "all"));
foreach($screens as $screen) {
$meta_query[] = [
'key' => '_av_meta_key_' . $screen->id,
'value' => 'yes',
'compare' => '='
];
}
$args = array(
'post_type' => 'advertisements',
'meta_query' => $meta_query,
);
I'm trying to add the "duplicate" post option to my custom post type admin menu called events. I have searched online, but there is very little documentation on how to add this function to the custom post types. Perhaps I am using the incorrect terminology when searching.
The code below adds the "duplicate" function, but when clicked it doesn't actually duplicate the post but returns a white screen instead. Are there any pointers or tips that you can give me?
function rd_duplicate_post_link( $actions, $post ) {
if (current_user_can('edit_posts') || $post->post_type=='events') {
$actions['duplicate'] = 'Duplicate';
}
return $actions;
}
add_filter('page_row_actions', 'rd_duplicate_post_link', 10, 2)
You need to call admin_action_rd_duplicate_post_as_draft hook
function rd_duplicate_post_link( $actions, $post ) {
//print_r($actions);
//if (current_user_can('edit_posts') || $post->post_type=='movies') {
$actions['duplicate'] = 'Duplicate';
// }
return $actions;
}
add_filter('page_row_actions', 'rd_duplicate_post_link', 10, 2);
add_action( 'admin_action_rd_duplicate_post_as_draft', 'dt_dpp_post_as_draft' );
function dt_dpp_post_as_draft()
{
global $wpdb;
/*sanitize_GET POST REQUEST*/
$post_copy = sanitize_text_field( $_POST["post"] );
$get_copy = sanitize_text_field( $_GET['post'] );
$request_copy = sanitize_text_field( $_REQUEST['action'] );
$opt = get_option('dpp_wpp_page_options');
$suffix = !empty($opt['dpp_post_suffix']) ? ' -- '.$opt['dpp_post_suffix'] : '';
$post_status = !empty($opt['dpp_post_status']) ? $opt['dpp_post_status'] : 'draft';
$redirectit = !empty($opt['dpp_post_redirect']) ? $opt['dpp_post_redirect'] : 'to_list';
if (! ( isset( $get_copy ) || isset( $post_copy ) || ( isset($request_copy) && 'dt_dpp_post_as_draft' == $request_copy ) ) ) {
wp_die('No post!');
}
$returnpage = '';
/* Get post id */
$post_id = (isset($get_copy) ? $get_copy : $post_copy );
$post = get_post( $post_id );
$current_user = wp_get_current_user();
$new_post_author = $current_user->ID;
/*Create the post Copy */
if (isset( $post ) && $post != null) {
/* Post data array */
$args = array('comment_status' => $post->comment_status,
'ping_status' => $post->ping_status,
'post_author' => $new_post_author,
'post_content' => $post->post_content,
'post_excerpt' => $post->post_excerpt,
'post_name' => $post->post_name,
'post_parent' => $post->post_parent,
'post_password' => $post->post_password,
'post_status' => $post_status,
'post_title' => $post->post_title.$suffix,
'post_type' => $post->post_type,
'to_ping' => $post->to_ping,
'menu_order' => $post->menu_order
);
$new_post_id = wp_insert_post( $args );
$taxonomies = get_object_taxonomies($post->post_type);
if(!empty($taxonomies) && is_array($taxonomies)):
foreach ($taxonomies as $taxonomy) {
$post_terms = wp_get_object_terms($post_id, $taxonomy, array('fields' => 'slugs'));
wp_set_object_terms($new_post_id, $post_terms, $taxonomy, false);}
endif;
$post_meta_infos = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id=$post_id");
if (count($post_meta_infos)!=0) {
$sql_query = "INSERT INTO $wpdb->postmeta (post_id, meta_key, meta_value) ";
foreach ($post_meta_infos as $meta_info) {
$meta_key = $meta_info->meta_key;
$meta_value = addslashes($meta_info->meta_value);
$sql_query_sel[]= "SELECT $new_post_id, '$meta_key', '$meta_value'";
}
$sql_query.= implode(" UNION ALL ", $sql_query_sel);
$wpdb->query($sql_query);
}
/*choice redirect */
if($post->post_type != 'post'):$returnpage = '?post_type='.$post->post_type; endif;
if(!empty($redirectit) && $redirectit == 'to_list'):wp_redirect( admin_url( 'edit.php'.$returnpage ) );
elseif(!empty($redirectit) && $redirectit == 'to_page'):wp_redirect( admin_url( 'post.php?action=edit&post=' . $new_post_id ) );
else:
wp_redirect( admin_url( 'edit.php'.$returnpage ) );
endif;
exit;
} else {
wp_die('Error! Post creation failed: ' . $post_id);
}
}