I want to query post based on post object sub field but not the post_id - advanced-custom-fields

I have 2 acf custom post type
target_crop
product
Plugins that I am using: Custom Post Type UI, Advanced Custom Fields and ACF to REST API
target_crop: There is one field call target_crop(text)
product: There are 3 fields product_name(text), technical_composition(text), target_crop(post_object->ref to target_crop)
When I hit {{url}}/target_crop I get this below response from the ACF to Rest API which is fine.
And when I hit {{url}}/product I get this below response
Now what I want is I want to add a filter like {{url}}product?target_crop=Rice so it will only show the data for that target_crop.
I have tried adding meta query
if(isset($_GET['target_crop']) && !empty($_GET['target_crop'])){
$meta_query['meta_query'][] = [
'key' => 'target_crop',
'value' => $_GET['target_crop'],
'compare' => 'LIKE'
];
}
But it is not showing anything at all.
On the other hand instead of {{url}}product?target_crop=Rice if I add {{url}}product?target_crop=70 70 which is the id for rice then it showing perfectly fine.
I want to query post based on post object sub field but not the id.

Related

CakePHP 4 do not get new added fields from DB

I have some trouble getting content of a new created field from Database.
At the beginning i created my "Menue" table in phpmyadmin and then in cake with "bin/cake bake all Menue". So far so good. But i forgot a field "price" which i added right now in the database and filled it with content.
In cake i added this field "price" in src/Model/Entitiy/Menue and src/Table/MenuesTable.php. In the Controller src/Controller/MenuesController i wanted to get the price with $menue->price but there is no field key or content. Also print_r($menue); return all other fields and content but not the price field.
is there another file where i have to add this field?
In phpmyadmin i can do a simple sql statement and i get this field with content in the results... so i am thinking cake is missing something.
Thanks in advance!
The following query was created by the bake command.
$menue = $this->Menues->get($id, [
'contain' => ['Restaurants'],
]);
also a self written query do do deliver the field "price"
$menue = $this->Menues
->find()
->where(['id ='=>$id]);
foreach($menue as $m){
print_r($m);
}
I just figured out, that this field and a again newly created "test" field are loaded in another Controller written by hand with
$this->loadModel('Menues');
...
$contents = $this->Menues
->find()
->select(['id',
'title',
'short_description',
'additives',
'price',
'currency',
'image_path'
'test'
])
->where(['restaurant_id =' => $restaurant_id,'menuegroup' => $cat['menuegroup']])
->order(['sort_order' => 'ASC']);
But why my other controller do not want to give me the price is still a question i can not answer. maybe someone knows.
THX

How to access /posts WordPress JSON REST API and filter by post_type?

I have a number of posts in the table wp_3_posts with the post_type "people". This post_type is created using the Admin Columns plugin.
How do I retrieve these?
The documentation for Posts offers filtering by categories or tags but post_type is neither of these.
https://developer.wordpress.org/rest-api/reference/posts/
Thank you :]
If I got your question the right way, you want to get posts of a custom post type with REST API.
You have to set show_in_rest and public in the arguments when you create the custom post type in wordpress.
add_action( 'init', 'my_cpt' );
function my_cpt() {
$args = array(
'public' => true,
'show_in_rest' => true,
'label' => 'My Custom Post'
);
register_post_type( 'mycustompost', $args );
}
More about this: https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-rest-api-support-for-custom-content-types/
With that having set, you can get the posts of post type with using the right parameters in the url.
So if you just want to get posts, you can use:
https://yoursite.com/wp-json/wp/v2/mycustompost?per_page=10
I would suggest setting the per_page to have control if you are getting a lot of posts.
You can also have access to more data without additional HTTP requests using _embed
https://yoursite.com/wp-json/wp/v2/mycustompost?per_page=10&_embed=wp:term,wp:featuredmedia
For example, with this you get taxonomy terms and urls of different featured image sizes.
So you do not need to get all posts (and post types) of your website and then filter by post type, but just get posts of this post type instead. You can than do more filtering using global parameters:
https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/
With VueJS (in my opinion better performance) this would look something like:
fetch("https://yoursite.com/wp-json/wp/v2/mycustompost?per_page=10")
.then(response => response.json())
.then((data => {
this.mycustompost = data;
}))
Or if using standard javascript something like:
let state = {
posts: [],
baseUrl: 'https://yoursite.com/wp-json/wp/v2/mycustompost',
perPage: '?per_page=10',
wpFetchHeaders: {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Expose-Headers': 'x-wp-total'
}
}
}

Magento 1.9 add custom column to associated products grid

We have an existing customization that appears to have broken when we upgraded from 1.7 to 1.9 community.
The customization adds a column to the associated products grid.
The customization is a local override of
app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Group.php
This was done before I started on the project
$this->addColumn('breakdown_part_no', array(
'header' => Mage::helper('catalog')->__('Part No'),
'name' => 'breakdown_part_no',
'type' => 'varchar',
'index' => 'breakdown_part_no',
'width' => '120px',
'editable' => true,
));
This was added to _prepareColumns()
Another customization was added to method getSelectedGroupedProducts()
public function getSelectedGroupedProducts()
{
$associatedProducts = Mage::registry('current_product')->getTypeInstance(true)
->getAssociatedProducts(Mage::registry('current_product'));
$products = array();
foreach ($associatedProducts as $product) {
$products[$product->getId()] = array(
'qty' => $product->getQty(),
'position' => $product->getPosition(),
'breakdown_part_no' => $product->getBreakdownPartNo(),
);
}
return $products;
}
The behavior is that the column appears in the admin and can be edited, however when saved, it does not save any value.
If I modify the getSelectedGroupedProducts part and set a hard coded value, it displays still no value (blank field), but interestingly if I click save with no value, it saves the value that was hard coded. If I enter any value in the field, it saves as a blank. This is really strange behavior that makes no sense to me.
If I change one of the other fields, such as position to be a hard coded value, it appears instantly and works as expected. Please let me know the proper way for this to work.
There are several posts on various forums about how to do the above and the modification mentioned is true, but what all of the other posts left out was the adminhtml layout input. When a user edits product data in Magento Admin (Associated Products), the data is serialized and sent to the controller save action. I noticed that the fields were not present when a value was entered. This is because the value wasn't in the layout so it was being stripped off of the request before it was posted to the controller.
Add input field in adminhtml/default/default/layout/catalog.xml
adminhtml_catalog_product_supergroup
addColumnInputName

Cakephp 3: Modifying Results from the database

In my database there is a content table and when fetching data from this table I would like to append field url to the results, which is based on slug field which is contained in the table. Anyway, I have seen a way to do this in the previous versions of cakephp using behavior for the model of this table and then modifying results in afterFind callback in the behavior class. But in version 3 there is no afterFind callback, and they recommend using mapReduce() method instead in the manual, but this method is poorly explained in the manual and I cant figure out how to achieve this using mapReduce().
After little bit of research I realized that the best way to append the url field field to find results is using formatResults method, So this is what I did in my finders:
$query->formatResults(function (\Cake\Datasource\ResultSetInterface $results) {
return $results->map(function ($row) {
$row['url'] = array(
'controller' => 'content',
'action' => 'view',
$row['slug'],
$row['content_type']['alias']
);
return $row;
});
});

Minimising Database Queries in Wordpress when using Advanced Custom Fields

I'm working on a page which lists staff members for a large company and trying to minimise the number of times I'm forced to query the database as it gets quite complex and slow.
'person' is a custom post type (there are about 300 people)
'date_accredited' is a date field added via Advanced Custom Fields plugin.
Only accredited staff will have a 'date_accredited'.
I need to list every 'person' BUT, with ALL accredited staff listed first (so about 20 accredited staff come at the top).
At the moment, I am doing a call to WP_Query like:
$args = array(
'posts_per_page' => -1,
'post_type' => 'people',
'no_found_rows' => true,
'meta_key' => 'date_accredited'
);
$people = new WP_Query($args);
After that I'm doing:
while($people->have_posts()): $people->the_post();
$my_post_meta = get_post_meta($post->ID, 'date_accredited', true);
if (!empty($my_post_meta)) {
array_push($accredited, $post);
} else {
array_push($notAccredited, $post);
}
endwhile;
Leaving us with two arrays of 'person' objects. My thinking here was that I would be able to do something like the following to get the list I want:
foreach($accredited as $person):
personTile($person);
endforeach;
foreach($notAccredited as $person):
personTile($person);
endforeach;
I'm trying to avoid re-querying the database.
The personTile(); function was supposed to output various info and HTML (the_post_thumbnail() and various Advanced Custom Fields fields), but what I'm realising now is that none of this is included in the post objects I get from WP_Query(), so I'm forced to use things like:
get_the_post_thumbnail($person->ID)
get_permalink($person->ID)
get_field('date_accredited', $person->ID)
All of these cost another DB Query (each!), and worse still since they are in a loop each one happens around 300 times.
Is there any way to get the permalink, thumbnail and ACF fields to be included in the original DB Query? Would I need to resort to a custom MySQL Query???
Any other suggestions welcome!