Contentful: how to query entries that have one of either entries attached? - php

I'm trying to filter blog posts based on 2 or more categories.
The blog posts are a content type and the categories are as well. Each blog post can have only one category. The category is connected to the post via a reference field. I'd like the user to be able to filter the posts. The user can select multiple categories at once.
It seems I'm unable to fabricate the query. Here's what I have so far:
// PHP
$categories = ["79RwpuYXo4W9FiYMdpeShj", "4CAkZRYSa3EB23ipTwZ92R"];
$query = (new Query)
->setContentType('blogPosts')
->where('fields.postCategory.sys.id', $categories, 'in'); // using 'all' instead of 'in' also doesn't return any results
In my mind, this should get all blog posts that hold a reference to either category entry (id). However, no entries are returned using this query. I'm using contentful/laravel v4.0.

Okay, I figured it out. I'm using Contentful Core v2. The correct query structure for v2 is the following:
// PHP
$categories = ["79RwpuYXo4W9FiYMdpeShj", "4CAkZRYSa3EB23ipTwZ92R"];
$query = (new Query)
->setContentType('blogPosts')
->where('fields.postCategory.sys.id[in]', $categories);

Related

How to get the length of an array of posts matching meta_query in WordPress?

I have a custom post type called 'service-area'. On one of the pages in particular, I am trying using a meta query to filter out the posts that it gets. That works fine.
I then use:
$serv_areas = get_posts($args);
Once again, I am able to get these posts without an issue using a foreach loop like this:
foreach($serv_areas as $post) {...}
But I am having a different issue. I would like to get the amount of posts that match the meta query. But when I use
sizeof($serv_areas) or count($serv_areas)
I get the total amount of posts, not just the posts that meet the criteria.
How is this possible? Am I missing something?
The get_posts() function returns a WP_Query.
https://codex.wordpress.org/Class_Reference/WP_Query#Properties
In that case, you should use the property $serv_areas->found_posts
$found_posts
The total number of posts found matching the current query parameters

Implement custom search by term name(s) in wordpress

I have implemented normal search functionality in simple pages using php and MySQL where I get result rows by mysqli_fetch_array. There I could have any numbers of variable with AND or OR relationship and it will retrieve results from the db.
Now I am trying to do this in WordPress.
I have seen solutions where one uses WP_query to search by term names. How do I achieve this AND and OR variables in my search query.
For example, my query is like select all post title where term name like 'search keyword' AND term slug like 'hi'.
I have created a view terms_and_posts table from merging terms and posts tables using taxonomy relationship, with columns custom term name, custom term slug, post title, post content, post status, and post type.
Do I need a merged table or it can be achieved by modifying WP_Query?
I do not want to resort to using plugins as I am very new to WordPress, and I prefer not to use plugins as long as I can help it.

Fetch results based on parameter WordPress

I'm attempting to customize a wordpress theme. I've added custom field cp_job with form submission. This indicates if the ad is either Buyer(Buying services) or Seller(selling services), which is now complete.
Now I want to fetch results based on buyer or seller. In this wordpress theme classipress they have "Ads" on the side:
I simply want to fetch ads which have the attribute buyer or seller, which I assume is under the MySQL column cp_job. These ads will return the ad with all columns. Doing this in native PHP and MySQL would be easy but working around this theme/wordpress is way more complicated as I don't understand WordPress syntax.
You can use wordpress custom query to fetch record from any table.Like
global $wpdb;
// return array of object
$dataArr = $wpdb->get_results(" SELECT col FROM table WHERE cond = data ");
Then you can do foreach on records like below:
foreach( $dataArr as $data ){
echo $data->col;
}
Hope this helps ;)
Cheers!!!

Full text search including tags

This isn't entirely exclusive to cakephp but that's the framework im using so any help by thateans would be great..!
I have a MySQL table of posts, tags and post_tags to associate the two together.
I've set up my full text fields on my posts table to be the body and title but I wanted to include the associated tags into my searching too and order the posts based on where the search query mathes any of the tags assigned to the posts.
Would I need to build a hefty SQL query for this perhaps? Also if anyone could offer a cakephp specific solution I'd also like to cache the searches too using the inbuilt cache methods...
Many thanks!
Use the "find" function in CakePHP:
$result = $this->Post->find('all', array('conditions' => array('Post.body LIKE' => '%search_text%')));
If you want more information from a query put this line before "find" function:
$this->Post->recursive = 2; //or 1
In $result you should get all tags which belongs to the founded Posts.

Mysql parent child tables reducing database calls or merge in PHP

If I had 2 tables, say blog_category and blog, each "blog" can belong in a particular category only so a 1-1 relationship based on a key called "blog_category_id".
Now in my code I would do something like:
//Loop through categories such as
foreach($categories as $cat):
//then for each category create an array of all its posts
$posts = $cat->getPosts(); // This would be another DB call to get all posts for the cat
//do stuff with posts
endforeach;
Now to me this seems like it could end up quite expensive in terms of DB calls depending on the size of $categories. Would this still be the best solution to do this? Or would I be able to do something in the code and first retrieve all the categories, then retrieve all the blogs and map them to their corresponding category via the id somehow? This would in theory be only 2 calls to the DB, now size wise the result set for call 2 (the blogs) would definitely be larger, but would the actual DB call be as expensive?
I would normally go for the first option, but I'm just wondering if there would be a better way of approaching this or is it more likely that the extra processing in PHP would be more costly in terms of performance? Also specifically from an MVC perspective, if the model returns the categories, but it should also return the corresponding blogs for that category, I'm not sure how best to structure this, from my understanding, shouldn't the model return all the data required for the view?
Or would I be better off selecting all categories and blogs using inner joins in the first query and create the output I need of this? Perhaps by using a multi-dimensional array?
Thanks
You can use a simple SQL query to get all categories and posts like the following:
SELECT *
FROM posts p
JOIN categories c ON c.id = p.blog_category_id
ORDER BY c.category_name ASC,
p.posted_date DESC
Then when you loop over the returned records assign the current category id to a variable, which you can use to compare against the next records category. If the category is different then print the category title before printing the record. It is important to note that for this to work you need to get the posts ordered by category first and then post so that all posts in the same category are together.
So for example:
$category_id = null;
foreach($posts as $post) {
if($post['blog_category_id'] != $category_id) {
$category_id = $post['blog_category_id'];
echo '<h2>' . $post['category_name'] . '</h2>';
}
echo '<h3>' . $post['post_title'] . '</h3>';
echo $post['blog_content'];
}
Note: as you have not posted up the schema of these two tables I have had to make up column names that are similar to what I would expect to see in code like this. So the code above will not work with your code without some adjustments to account for this.
The best solution depends on what you are going to do with data.
Lazy loading
Load data when you need it. It's a good solution when you have, for instance, 20 categories and you load posts for only 2 of them. However, if you need to load posts for all of them it won't be efficient at all... It's called a n+1 queries (and it's really bad).
Eager loading
On the other hand, if you have to access to almost all of your posts, you should do an eager loading.
-- Load all your data in a query
SELECT *
FROM categories c
INNER JOIN posts p ON c.id = p.category_id;
// Basic example in JSON of how to format your result
{
'cat1': ['post1', 'post2'],
'cat2': ['post5', 'post4', 'post5'],
...
}
What to do?
In your case I would say an eager loading because you load everything in a loop. But if you don't access to the most of your data, you should re-design your model to perform a lazy loading in such a way that the SQL query to load posts for a specific category is actually performed when a view try to access them.
What do you think?

Categories