Question:
I’m trying to show posts only from the “News” category, but the error below always appears. Does anyone have an idea?
Product:
Wix Editor, Velo
Additional information:
import wixData from 'wix-data';
import wixLocation from 'wix-location';
// Função para obter IDs dos posts da categoria "Notícias"
function getPostsFromNewsCategory() {
return wixData.query('Blog/Categories')
.eq('Label', 'Notícias')
.find()
.then(results => {
if (results.items.length > 0) {
return JSON.parse(results.items[0].Posts); // Convertendo a string JSON para array de IDs
} else {
return [];
}
})
.catch(error => {
console.error("Erro ao consultar a categoria:", error);
return [];
});
}
// Função para obter os posts por IDs
function getPostsByIds(postIds) {
return wixData.query('Blog/Posts')
.hasSome('_id', postIds)
.find()
.then(results => {
return results.items;
})
.catch(error => {
console.error("Erro ao consultar posts:", error);
return [];
});
}
// Função para truncar texto
function truncateText(text, maxLength) {
if (text.length > maxLength) {
return text.substring(0, maxLength) + '...';
}
return text;
}
// Função para carregar e exibir posts da categoria "Notícias"
function loadNewsPosts() {
getPostsFromNewsCategory()
.then(postIds => {
if (postIds.length > 0) {
return getPostsByIds(postIds);
} else {
console.log("Nenhum post encontrado na categoria Notícias.");
return [];
}
})
.then(posts => {
if (posts.length > 0) {
let displayedPostIds = [];
posts.forEach((post, postIndex) => {
if (!displayedPostIds.includes(post._id)) {
let truncatedTitle = truncateText(post.title, 3 * 40);
$w("#postNewsTitle" + postIndex).text = truncatedTitle;
$w("#postNewsSubTitle" + postIndex).text = truncatedTitle;
let postUrl = post.postPageUrl; // Substitua pelo caminho real para os seus posts
$w("#postNewsTitle" + postIndex).onClick(() => {
wixLocation.to(postUrl);
});
displayedPostIds.push(post._id);
}
});
} else {
console.log("Nenhum post encontrado na categoria Notícias.");
}
})
.catch(error => {
console.error("Erro ao carregar posts da categoria Notícias:", error);
});
}
// Chame a função para carregar os posts ao carregar a página
$w.onReady(function () {
loadNewsPosts();
});