WordPress - Hide table rows on condition - wordpress

I have a custom CPT called Topics and only an editor or admin can create one. There are custom columns and custom meta box. It is only made for the backend purpose, not for publishing. So, it has a meta box and it will have a list of authors and selecting one will assign it to the author and will display in the name will be displayed in the table that has a custom column name Author. So, I want authors to see only those topics that has been assigned to them via meta box. Other Topics should be hidden. Is there a way to hide specific rows with the condition. 'cruiser_writer_value_key' will save the name of the author. So my condition is.
$writer_list_value = get_post_meta( $post_id, 'cruiser_writer_value_key', true );
$current_user = wp_get_current_user();
if($current_user->display_name == $writer_list_value){
//display post row
}
else{
//hide post row of the column
}
I'm really stuck in this. And Yeah I have custom columns too. It's just that I don't want to the author to edit or read Topics that have not been assigned to them.
So, my custom CPT is like this and the custom columns are there. See the picture for more details.

Use filter_posts_list to filter the posts
add_action('pre_get_posts', 'filter_posts_list');
function filter_posts_list($query)
{
//$pagenow holds the name of the current page being viewed
global $pagenow, $typenow;
$user = wp_get_current_user();
$allowed_roles = array('author');
//Shouldn't happen for the admin, but for any role with the edit_posts capability and only on the posts list page, that is edit.php
if(array_intersect($allowed_roles, $user->roles ) && ('edit.php' == $pagenow) && $typenow == 'your_custom_post_type')
{
//global $query's set() method for setting the author as the current user's id
$query->set(
'meta_query', array(
array(
'key' => 'yout_meta_key',
'value' => $user->display_name,
'compare' => '==',
),
)
); // here you can set your custom meta field using meta_query.
}
}

Related

Post meta to custom field with multiple rows! - Wordpress

I'm using the houzez theme and trying to develop a plugin to post from an API to a "property" post. "Property" is a custom post and one custom field (additional_feature) has multiple rows.
When I get the value from additional_feature using get_post_meta() in a sample post with the fields already filled we get:
Array ( [0] => Array ( [0] => Array ( [fave_additional_feature_title] => aaa
[fave_additional_feature_value] => 234 ) [1] => Array (
[fave_additional_feature_title] => bbb [fave_additional_feature_value] => 567
) [2] => Array ( [fave_additional_feature_title] => ccc
[fave_additional_feature_value] => 890 ) ) )
So, the custom field additional_feature has some more fields inside!! When I use update_post_meta it doesn't work. I tried setting up an array to pass the data exactly as the sample array looks like when called trough get_post_meta(). However, it doesn't work.
Any idea of how to update additional_feature?
*To output repeater meta (Is used - ACF custom field repeater).
$meta = get_post_meta($post->ID); //Get all post meta per one request
$repeater_count = $meta["additional_feature"][0]; //Count of iteration
for ($i=0; $i<$repeater_count; $i++) {
$feature_title = 'additional_feature_'.$i.'_title';
echo $meta[$feature_title][0]; //Output repeater meta
}
*To update repeater meta (Use ACF custom field repeater). Update on save post.
You can change the code for your needs
!!!Generate the working code better on the test site, because with erroneous names of the user fields, when saving the post, new fields will be created in the database table - post_meta.
Add to functions.php
add_filter('acf/save_post', 'main_meta_filter', 20);
function main_meta_filter($post_id) {
if ( $post_id != 7 ) //You can use post type if you need
return;
//Repeater
$number_rows = get_post_meta( $post_id, "additional_feature" );//Count of iteration
for ($i=0; $i<$number_rows[0]; $i++) {
$key = 'additional_feature_'.$i.'_title';
//To get old value use $old_value = get_post_meta($post_id, $key, false);
//and output use $old_value[0]
$new_value = 1;//You custom value
update_post_meta($post_id, $key, $new_value);
}
}
Something weird happened. I re-tried a method that didn't work but I had no more ideas. I used the following code:
$data = array(
array(
'fave_additional_feature_title' => 'Ax',
'fave_additional_feature_value' => 111,
),
);
update_post_meta($postid, 'additional_features', $data);
It worked this time. Very weird and I dont know how it didn't work before and now it works. However, now I can update the custom field.

WooCommerce - include custom fields in the search function

So I'm looking to include the functionality of displaying content by its custom fields as well as its title and content.
I need to be able to search for orders, as well as subscriptions, on WooCommerce by custom field as well as the normal method. Is there any way I can, without adding additional search forms or booleans, simply get Wordpress to display posts that match with the search term by their custom fields, too?
I have used the following code thanks to a responder on here:
function custom_search_query( $query ) {
$custom_fields = array(
// put all the meta fields you want to search for here
"gender",
"birthdate"
);
$searchterm = $query->query_vars['s'];
// we have to remove the "s" parameter from the query, because it will prevent the posts from being found
$query->query_vars['s'] = "";
if ($searchterm != "") {
$meta_query = array('relation' => 'OR');
foreach($custom_fields as $cf) {
array_push($meta_query, array(
'key' => $cf,
'value' => $searchterm,
'compare' => '=='
));
}
$query->set("meta_query", $meta_query);
};
}
add_filter( "pre_get_posts", "custom_search_query");
This works great when searching orders, but what I need to search is subscriptions, where it doesn't work.
Help would be much appreciated!

Event Espresso Query Modification?

I am using Event Espresso with WordPress.
May u help me out in further query modification?
Hope you will :)
I want to use meta_query to list events on page.
Somewhat like below code.
$atts = array(
'title' => NULL,
'limit' => 10,
'css_class' => NULL,
'show_expired' => FALSE,
'month' => NULL,
'category_slug' => NULL,
'order_by' => 'start_date',
//'order_by' => 'end_date',
'sort' => 'DESC',
'meta_query' => array(
array(
'key' => 'start_date',
'value' => '2017-01-08 08:00:00',
'type' => 'DATETIME',
'compare' => '>=',
),
)
);
I want to implement search functionality for Event Espresso and i have those fields:
State - Dropdown (How to list all state? May be Venue)
Category - Dropdown
Start Date - Datepicker
End Date - Datepicker
Keyword - input
On submit those values will be submitted and based on those , i will get filtered events that are related with those values.
So how to implement this?
Please help.
Thanks in Advance
A slightly delayed response to this...
First, this depends on the version of EE you're using. They support both EE3 and EE4. I use EE4, so any reference to code I make is specific to version 4.
In order to create an events archive with a filtering functionality, you'd need to use the EE events archive. EE uses custom database tables and a lot of different post types to achieve what you see, so creating a simple archive with these filters won't work very well. Very little is stored in the _posts and _postmeta tables and you need to get post meta from related post types and tables that aren't laid out like WP_Query likes. They have a shortcode for the events list, which is laid out here and has a lot of the filters you're looking for, but no search functionality.
Their support forum has a lot of snippets and such created by their staff and there's a (long) related post about formatting the events archive page here. You'll also need to go through this documentation to see about their custom methods and hooks.
You could copy over and modify the archive templates they describe in a child theme to add search functionality to the top of the page. This would allow you to directly override the archive. You'll need to make use of some fancy filters, which are covered pretty clearly over on WPMU Dev.
The pieces of information you're looking for for filtering are here, minus keyword:
<?php
if( have_posts() ){
while ( have_posts() ){ the_post(); // enter the WordPress loop
$id = get_the_ID(); // get the ID of the current post in the loop, post ID = EVT_ID
$terms = get_the_terms( $id, 'espresso_event_categories' ); // get the event categories for the current post
if ( $terms && ! is_wp_error( $terms ) ) {
$cats = array();
foreach ( $terms as $term ) {
// do something
}
}
$event = EEM_Event::instance()->get_one_by_ID( $id ); // get the event OBJECT using EE's existing method
$venue = $event->venue(); // get the venue object for the current event
$state = $venue instanceof EE_Venue ? $venue->state_abbrev(); // get the event venue's state, but you can use state_name() to get the full name
// using the event to get the first and last date for the entire event. Sub $datetime for $event to do it per datetime
$start_date = $event->start_date('j M Y');
$end_date = $event->end_date('j M Y');
$start_time = $event->start_time(get_option('time_format'));
$end_time = $event->end_time(get_option('time_format'));
?>
<!-- Do some awesome layout stuff here -->
<?php
}
}
espresso_pagination();
?>
This will give you the meta for each post within the loop as variables, but you may want to pull them into pre_get_posts. You can just as easily create an array of $events and then filter it using the variables.
I'm not sure what your exact needs are regarding keyword. Do you mean tags? Title keywords? Description search? You'll need to narrow down exactly what you need this to do in order to write a function for it.

Woocommerce custom fields for shipping calculator

I'm building a custom shipping method for Woocommerce, and the one thing I'm totally hung up on is how to pass custom values to the calculate_shipping() function, either when it's being used on the Cart page or Checkout page.
I need to pass a handful of user-defined variables that will impact the quote -- ie "Is Residential Address", "Is Trade Show", etc etc.
calculate_shipping receives the $package array which contains a 'destination' array, but this only includes the standard add1, add2, city, state, zip, country info. I've added custom fields to the checkout page under both billing and shipping but I still can't figure out how to make these values accessible to the calculate_shipping function.
I've added a custom field like so:
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
$fields['shipping']['is_residential'] = array(
'label' => __('Residential Address?', 'woocommerce'),
'type' => 'checkbox',
'required' => false,
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
And I see this field show up on the Shipping section of the checkout form. However, I'm not seeing how I can access it anywhere. Even doing a print_r($_POST) on the checkout page doesn't show this field as being part of the post data, even after I know the form has been updated and re-posted.
But most importantly, I need to add the contents of the submitted field into the $package object which Woocommerce passes to a shipping method's calculate_shipping() function.
I'm just really not sure where to even start with this.
You can't expect to add checkout fields and have them available at the cart page.
The correct way is to use cart packages.
Check function get_shipping_packages() from class-wc-cart.php
public function get_shipping_packages() {
// Packages array for storing 'carts'
$packages = array();
$packages[0]['contents'] = $this->get_cart(); // Items in the package
$packages[0]['contents_cost'] = 0; // Cost of items in the package, set below
$packages[0]['applied_coupons'] = $this->applied_coupons;
$packages[0]['destination']['country'] = WC()->customer->get_shipping_country();
$packages[0]['destination']['state'] = WC()->customer->get_shipping_state();
$packages[0]['destination']['postcode'] = WC()->customer->get_shipping_postcode();
$packages[0]['destination']['city'] = WC()->customer->get_shipping_city();
$packages[0]['destination']['address'] = WC()->customer->get_shipping_address();
$packages[0]['destination']['address_2'] = WC()->customer->get_shipping_address_2();
foreach ( $this->get_cart() as $item )
if ( $item['data']->needs_shipping() )
if ( isset( $item['line_total'] ) )
$packages[0]['contents_cost'] += $item['line_total'];
return apply_filters( 'woocommerce_cart_shipping_packages', $packages );
}
You gotta hook into woocommerce_cart_shipping_packages filter and add your fields there.
Most likely you will need to add them (your fields) at the shipping calculator and checkout pages.
Hope this helps.

Wordpress set default title when creating a new custom post

I have a custom post type with just two (text)fields: an ISBN number and a youtube url by using 'supports' => array('title') when creating my custom post type.
The problem is, I don't need a title. So when I save my post, I made it so that the title becomes the ISBN number.
add_filter('wp_insert_post_data', array($this, 'change_title'), 99, 2);
function change_title($data, $postarr) {
if ($data['post_type'] == 'book_video') {
// If it is our form has not been submitted, so we dont want to do anything
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return $data;
// Verify this came from the our screen and with proper authorization because save_post can be triggered at other times
if (!isset($_POST['wp_meta_box_nonce']))
return $data;
// Combine address with term
$title = $_POST['_bv_isbn'];
$data['post_title'] = $title;
}
return $data;
}
This works, but the problem is, when I save the post WITHOUT prefilling a title (anything at all) the post is not saved, the title change function is not called, and all of my fields are reset.
Is it possible to set a default value to the title and hide it ?
When you register your custom post type, you can set what it supports, including the title.
When you call register_post_type(), add another entry to $args called supports and set it's value to an array. You can then pass a list of elements you want that post type to support. The default is 'title' and 'editor', but there are a host of options to choose from.
For example:
<?php
register_post_type(
"myCustomPostType",
array(
'supports' : array(
'editor',
'author',
'custom-fields'
)
)
)
?>
So long as you miss out title then you won't have to define one for each post.
For more information, visit this page: http://codex.wordpress.org/Function_Reference/register_post_type#Arguments

Resources