I can get all the posts using this query. What I want to do is to add custom field key and value so that I will able to pass it along with the post object.
$args = array(
'p' => 996,
'status' => 'publish',
'post_type' => 'ajde_events',
'tax_query' => array(
array(
'taxonomy' => 'event_type',
'field' => 'slug',
'terms' => 'cursed-warriors',
),
),
);
$singlePost = new WP_Query($args);
while ($singlePost->have_posts()) : $singlePost->the_post();
endwhile;
If I query this $singlePost->posts I will have the result below
0: [,…]
0: {ID: 996, post_author: "1", post_date: "2019-11-13 11:15:09", post_date_gmt: "2019-11-13 11:15:09",…}
ID: 996
comment_count: "0"
comment_status: "open"
filter: "raw"
.....etc
I want to add something here
I want to know how I can add some keys there like
project_name: "some project"
Custom Fields can be used for this.
If you are using Gutenberg you will find them under the post's options in the post editor. Click the three dots on the top right, select options, toggle the custom fields on then hit the reload page button. After it loads back up you will see the custom fields metabox at the bottom of the editor.
If you are using classic then the custom fields toggle will be under screen options.
It looks like you have a good grasp of how to handle the data from there. You can use get_post_meta with the postID and the key you add or print all the post meta like you have done above.
What I understand is you want to create a field in your CPT then wants to pass its value in wp loop.
First register a metabox
Here you can do that
/**
* Register meta boxes.
*/
function nap_register_meta_boxes() {
add_meta_box('nap-1', __('NAP Details', 'nap'), 'nap_display_callback', 'nap_location');
add_meta_box('featured-nap-1', __('Featured NAP Location', 'featured-nap'), 'featured_nap_display_callback', 'nap_location');
}
add_action('add_meta_boxes', 'nap_register_meta_boxes');
/**
* Meta box display callback.
*
* #param WP_Post $post Current post object.
*/
function nap_display_callback($post) {
include plugin_dir_path(__FILE__) . '/nap-address-form-fields.php';
}
then add fields to it in nap-address-form-fields.php
<div class="nap_box">
<p class="meta-options nap_field">
<label for="project_name">Project Name</label>
<input id="project_name" value="<?php echo esc_attr(get_post_meta(get_the_ID(), 'project_name', true)); ?>" type="text" name="project_name">
</p>
</div>
Then now on main answer to your question , this is how you can pass it to query
$args = array(
'p' => 996,
'status' => 'publish',
'post_type' => 'ajde_events',
'meta_key' => 'project_name',
'meta_value' => 'some project',
'tax_query' => array(
array(
'taxonomy' => 'event_type',
'field' => 'slug',
'terms' => 'cursed-warriors',
),
),
);
I just found out that since $array->posts is an array of objects you need to do this in order to add new key and value to the result
foreach ($singlePost->posts as $po) {
$po->project_name = "My Project";
}
Related
I use the Woocommerce “Handpicked products” Block in Wordpress Gutenberg to create a showcase of 3 products on my Frontpage. I saw that Woocommerce does not use Shortcodes for that, but that the page itself includes a paragraph which looks like this:
<!-- wp:woocommerce/handpicked-products {"contentVisibility":{"image":true,"title":true,"price":false,"rating":false,"button":false},"orderby":"menu_order","products":[181,225,179]} /-->"
I want to dynamically change the products (randomly shuffle) upon page load. Unfortunately, in the whole PHP-classes HandpickedProducts, AbstractProductGrid, AbstractDynamicBlock etc I do not see a Hook to change the Render parameter dynamically...
So what I found as possible solution is: To directly replace the product attribute in the Wordpress Post itself, therefore I implemented this hook:
function my_the_post_action(&$pobj) {
$pobj->post_content = str_replace('[181,225,179]', '[225, 220, 222]', $pobj->post_content );
}
add_action('the_post', 'my_the_post_action' );
It is actually replaced in the wp:woocommerce/handpicked-products paragraph, but doesnt take effect. Why does Woocommerce not consider the new Product IDs as parameters to his rendered block?
Thanks!!
Instead of modifying the "Blocks" entered via Pageeditor upon Pageload within the Frontpage - I came up with a better and cleaner option IMHO - by simply rendering such a Block within a customer Shortcode.
The following code consists of first the part where I randomly pick 3 products from the Database which have the Product-Tag "Featured" set so that the user can decide himself which products are open for selection ... and then I create my "Handpicked Products" block and render it:
add_shortcode('my_featured_prods', function($atts, $content = null)
{
// Get list of all Woocommerce products by Tag
$args = array(
'post_type' => 'product',
'posts_per_page' => 3,
'orderby' => 'rand',
'tax_query' => array(
array(
'taxonomy' => 'product_tag',
'field' => 'slug',
'terms' => 'featured'
)
)
);
$products = new WP_Query($args);
$ids = [$fix];
foreach($products->posts as $p)
$ids[] = $p->ID;
// Shuffle array:
shuffle($ids);
// Output Hand Picked Products Widget with my settings ...
$args = (object) [
'editMode' => 0,
'contentVisibility' => (object) [
'image' => 1,
'title' => 1,
'price' => 0,
'rating' => 0,
'button' => 0,
],
'orderby' => 'random',
'products' => $ids,
'alignButtons' => 1,
];
$args = sprintf(
'<!-- wp:woocommerce/handpicked-products %s /-->',
json_encode( $args )
);
return do_blocks($args);
});
I have a custom post type "Product", I have created 4 checkbox option for a field "Select Category", User can select multiple option at a time. For Some reason I am not using taxonomy to classify products.
So when I do meta_query, it do not result anything. Basically, I have selected, category for every product in the custom post type "Product", but ACF store it's checkbox value in array, and the meta_query can't search that array as a whole. However it can search from an array. My code is as follows:
$args = array(
'post_type' => 'fproduct',
'meta_query' => array(
array(
'key' => 'select_product_categories',
'value' => array('Indoor Games', 'Property Management'),
'compare' => 'IN',
),
),
);
// query
$wp_query = new WP_Query( $args );
echo "<pre>"; print_r($wp_query); echo "</pre>"; die;
So how can I search so that checkbox can work, also I can not get the checkbox value on a template, as it for post type for different products.
I have solved my problem as the checkbox is stored in searialized array, so instead of 'IN', 'LIKE' will work, so here goes the query -
$args = array(
'post_type' => 'fproduct',
'meta_query' => array(
array(
'key' => 'select_product_categories',
'value' => array('"Indoor Games"', '"Property Management"'),
'compare' => 'LIKE',
),
),
);
In ACF checkbox, what value have you set?
Furthermore, using the IN operator, it does not work in these cases. Just try using the LIKE operator:
"compare" => "LIKE".
However, it is a totally wrong way to create a taxonomy in Wordpress, because in this way, you have to restructure all the queries and the system is much less powerful, because the database tables do not have relations between them.
i am developing a multivendor shop and i want the vendors to post products from a Template page. i am using Advance custom fields to achieve this functionality.
What i did by far is to create the page template and managed to display the form but i have some issue to validate the fields with the Product. i might need to create some functionalities ?
<?php
/**
* The template for displaying all pages.
* Template Name: Add Product Vendor
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site will use a
* different template.
*
* #package Bober
*/
?>
<?php
acf_form_head();
get_header();
?>
<div id="content">
<?php
global $woocommerce;
acf_form(array(
$post_title = 'field_5a60022b402e2',
$post_categ = 'field_5a60028e402e3',
$post_descrip = 'field_5a600384402e4',
$post_img = 'field_5a6005e1402e7',
$post_price = 'field_5a61207ce5226',
/*'post_title' =>true,
'post_content' => true,*/
'uploader' => 'basic',
'post_id' => 'new_post',
'fields' => array($post_title, $post_descrip, $post_categ,$post_price, $post_img),
'new_post' => array(
'post_status' => 'draft',
'post_type' =>'product',
),
/*'fields' => array('field_5a60022b402e2', 'field_5a60028e402e3', 'field_5a600384402e4', 'field_5a6005e1402e7'),*/
'submit_value' => 'Add product'
));
?>
</div>
<?php get_footer(); ?>
At this point i was able to asign the title of the product and the content of by using the code below based on ACF form documentation.
'post_title' =>true,
'post_content' => true,
How do i assign the Title value, the description value, price value and image to the product post ? I don't necesary look for someone to provide me a code to replace, i want to know how to do it, give me some ideas, or where to read on how to do it.
Thank you in advance!
First, do an in-depth read of how acf_form() works.
The acf_form() code for adding a product in woocommerce could look like this:
$options = array(
'post_id' => 'new_post',
'post_title' => true,
'post_content' => true,
'new_post' => array(
'post_type' => 'product',
'post_status' => 'draft'
),
'field_groups' => [$field_group_id],
'form' => true,
'return' => '%post_url%', // so they could be redirected to the product page in a draft state - i imagine?!
'html_submit_button' => '<input type="submit" value="%s" />',
'updated_message' => 'Product Created',
'submit_value' => 'Submit Product'
);
acf_form($options);
Regarding the featured image of the product, create an image field and use the code below to sync the field with the featured image. You can read more about this by checking the ACF API reference for acf/update_value
add_filter('acf/update_value/name=featured_image', function ($value, $post_id, $field) {
if ($value != '') {
update_post_meta($post_id, '_thumbnail_id', $value);
} else {
delete_post_thumbnail($post_id);
}
return $value;
}, 10, 3);
I would like to find out what is the way to filter posts of a specific category using custom fields. The result I want is exactly the same as the table here
. I have created a list like that and inside the table cells I have inserted three different custom fields each one containing a number of values. How can I use the same structure as above the list of forbes magazine and filter posts using drop down menus?
I think this documentation is pretty clear https://codex.wordpress.org/Class_Reference/WP_Meta_Query.
However i am not quite sure what you are asking for.
do you want to filter the HTML output or your wordpress database by custom field??
btw, if you want to filter the html output, then use jQuery, i used to filter over 2000 List in Table row using data-attribute;
Here is the jQuery Documentation, https://api.jquery.com/category/selectors/
if you want to filter and reorder the wordpress table using the meta value
To order the by meta value
$args = [
'meta_key' => '*meta_keyword*',
'orderby' => 'meta_value',
'order' => 'ASC'
];
meta_keyword need to change based your on meta_key, you can order them pretty much by every type of value, Date, int etc
to filter the table
$args['meta_query'] = [
[
'key' => 'meta_key',
'value' => 'filter_value',
'type' => 'str*',
'compare' => '=*'
]
];
'*' Depend on value type and your logic
Here some information
https://wordpress.stackexchange.com/questions/30241/wp-query-order-results-by-meta-value
Another answer
https://stackoverflow.com/a/24253081/3392555
Please find the similar example on my blog. Here I am filtering using the custom fields and category name and displaying those as a block in the home page.
http://www.pearlbells.co.uk/filter-posts-custom-fields-wp_query/
$args = array(
'category_name' => 'courses',
'orderby' => 'menu_order',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'front_page',
'value' => 'yes',
'compare' => 'LIKE',
))
);
$the_query = new WP_Query( $args );
Custom Post type name = Software,
Custom field name = version meta
This coding is done on single.php. $version is used for call the custom field value on single.php and filter the data by custom field value.
<?php $args = array('post_type' => 'software', 'showposts'=>'4', 'category_name' => '', 'orderby' => '','meta_query' => array(array('key' => 'version_meta','value' => $version = get_post_meta($post->ID, 'version_meta', true))));
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();?>
<div class="post_desc">
<div class="thumb thmbhome3">
<?php the_post_thumbnail();?>
</div>
<div class="title_des edu tthome3">
<div class="title edu_titl ttshome3">
<h1><?php the_title();?></h1>
</div>
</div>
</div>
<?php endwhile; ?>
So, I have a search form, that returns custom posts with wp_query. Now I need to find posts with a custom field and specific value: Lets say I have multiple checkboxes named catagories[]. So when I save them it makes a serialized array in db. Now I need to search in the front end posts with lets say value 11 in it. Array looks like that: a:3:{i:1;s:2:"11";i:2;s:2:"33";i:3;s:2:"33";}. So here comes the problem, how can I retrieve information from this serialized array to find all posts with value 11. My code is:
$args = array(
'post_type'=>'paibcresume',
'posts_per_page' => 10,
'paged' => $paged,
'meta_query' => array(),
'tax_query' => array(),
'orderby' => 'date',
'meta_key' => '',
'order' => 'DESC'
);
// BASIC SEARCH FORM
// Search by category
// rbsercategories
// rbwwcategoryhidden
if (isset($_GET['rbsercategories']) && !empty($_GET['rbsercategories'])) {
$args['meta_query'][] = array(
'key' => 'rbwwcategoryhidden',
'value' => $_GET['rbsercategories'],
'compare' => 'IN'
);
}
$the_query = new WP_Query( $args );
while ($the_query->have_posts() ) : $the_query->the_post();
This code works if values in data base are not a serialized array, just simple strings, but doesn't work with arrays so what do I have to do?
Ok, I didn't find the way to search thru serialized arrays, but I found the way to work around it.
So I didn't change any fields in admin, instead I added new with a loop. So I have this fields named rbwwcategoryhidden[], that create this array. I unserialized that array and created new fields for each value:
$wwCategory = get_post_custom_values('rbwwcategoryhidden');
foreach($wwCategory as $wwCategoryValue){$wwCategoryUnser = unserialize($wwCategoryValue);}
$rbWwCatSearchCounter='0';
foreach($wwCategoryUnser as $catId){
$rbWwCatSearchCounter++;
echo '<input type="text" name="rbwwcatforsearch'.$rbWwCatSearchCounter.'" id="rbwwcatforsearch'.$rbWwCatSearchCounter.'" value="'.$catId.'">';
}
So now I got new fields, I personaly have a limit of three fields (user can only check three checkboxes): rbwwcatforsearch1, rbwwcatforsearch2, rbwwcatforsearch3. And I added value to each field from that array: 11, 33 and 33.
And now I just changed the meta_query code in the front end, and it looks like that:
// Search by category
if (isset($_GET['rbsercategories']) && !empty($_GET['rbsercategories'])) {
$args['meta_query'][] = array(
'key' => array('rbwwcatforsearch1','rbwwcatforsearch2','rbwwcatforsearch3'),
'value' => (isset($_GET['rbsercategories'])?$_GET['rbsercategories']:array()),
'compare' => 'IN'
);
}
And it works just perfect :)