function configuracionQueryArgs($args, $paged, $userid, $currentuserid) { $identifier =…
- User
function configuracionQueryArgs(paged, current_user_id) { _POST['identifier'] ?? ''; args['posts']; args['similar_to'];
- Assistant
function configuracionQueryArgs(paged, current_user_id) { _POST['identifier'] ?? ''; args['posts']; args['similar_to'];
if ($args['post_type'] === 'social_post') {
$posts_personalizados = calcularFeedPersonalizado($current_user_id);
$post_ids = array_keys($posts_personalizados);
if ($paged == 1) {
$post_ids = array_slice($post_ids, 0, $posts);
}
$query_args = [
'post_type' => $args['post_type'],
'posts_per_page' => $posts,
'paged' => $paged,
'post__in' => $post_ids,
'orderby' => 'post__in',
'meta_query' => !empty($identifier) ? [['key' => 'datosAlgoritmo', 'value' => $identifier, 'compare' => 'LIKE']] : [],
];
} else {
$query_args = [
'post_type' => $args['post_type'],
'posts_per_page' => $posts,
'paged' => $paged,
'orderby' => 'date',
'order' => 'DESC',
];
}
// aqui en los resultados necesito que no incluya el post $similar_to, ($similar_to es la id del post del que se va a buscar publicaciones similares y no debe estar incluido, para que no aparezca 2 veces en la pagina)
// Manejar publicaciones similares
if ($similar_to) {
// Obtener los datosAlgotimo del post similar
$datosAlgoritmo = get_post_meta($similar_to, 'datosAlgoritmo', true);
if ($datosAlgoritmo) {
$data = json_decode($datosAlgoritmo, true);
$meta_queries = [];
$relation = 'OR'; // Puedes ajustar esto según cómo quieras combinar las condiciones
// Ejemplo: Coincidencia de BPM
if (!empty($data['bpm'])) {
$meta_queries[] = [
'key' => 'datosAlgoritmo',
'value' => '"bpm":' . $data['bpm'],
'compare' => 'LIKE',
];
}
// Coincidencia de Key
if (!empty($data['key'])) {
$meta_queries[] = [
'key' => 'datosAlgoritmo',
'value' => '"key":"' . $data['key'] . '"',
'compare' => 'LIKE',
];
}
// Coincidencia de Scale
if (!empty($data['scale'])) {
$meta_queries[] = [
'key' => 'datosAlgoritmo',
'value' => '"scale":"' . $data['scale'] . '"',
'compare' => 'LIKE',
];
}
// Coincidencia de Tags
if (!empty($data['tags']) && is_array($data['tags'])) {
foreach ($data['tags'] as $tag) {
$meta_queries[] = [
'key' => 'datosAlgoritmo',
'value' => '"' . $tag . '"',
'compare' => 'LIKE',
];
}
}
if (!empty($meta_queries)) {
$query_args['meta_query'] = array_merge($query_args['meta_query'], [
'relation' => $relation,
...$meta_queries
]);
// Excluir el post original
$query_args['post__not_in'][] = $similar_to;
}
}
}
if (!empty($args['exclude'])) {
$query_args['post__not_in'] = array_merge($query_args['post__not_in'] ?? [], $args['exclude']);
}
$query_args = aplicarFiltros($query_args, $args, $user_id, $current_user_id);
return $query_args;
}
Your PHP function configuracionQueryArgs is designed to construct query arguments for fetching posts, with special handling for posts of type social_post and for fetching similar posts while excluding the original post ($similar_to). I'll walk through your code, point out its strengths, and suggest a few improvements to ensure it works as intended.
Initial Setup:
identifier from $_POST.posts, similar_to, and post_type from the $args array.Handling social_post Type:
post__in with the personalized post IDs.$paged == 1).meta_query if an identifier is provided.Handling Other Post Types:
Handling Similar Posts ($similar_to):
datosAlgoritmo meta field from the reference post.meta_query to find similar posts based on bpm, key, scale, and tags.$similar_to) from the results.Excluding Additional Posts:
$args['exclude'].Applying Filters:
aplicarFiltros.$similar_toYour approach to excluding the $similar_to post is generally correct:
// Exclude the original post
$query_args['post__not_in'][] = $similar_to;
However, there are a few considerations and potential improvements to ensure robustness:
Initialization of post__not_in:
post__not_in, ensure it's initialized as an array. This prevents potential issues if it's not already set.Merging Exclusions:
$similar_to and $args['exclude']), ensure that all IDs are combined correctly without overwriting.Avoiding Duplicate Exclusions:
$similar_to is already included in $args['exclude'], ensure it doesn't lead to redundant exclusions.Here's a revised version of your function incorporating the above considerations:
Initialization and Defaults:
$posts and $post_type to ensure the function behaves predictably even if certain arguments are missing.post__not_in: Ensures that post__not_in is always an array before appending to it. This prevents potential errors when using the [] append syntax.Data Sanitization:
esc_sql() to sanitize string values before injecting them into the query. This helps prevent SQL injection vulnerabilities.bpm are cast to integers to maintain data integrity.Handling meta_query:
meta_query already exists (e.g., from the identifier), the function appends the new conditions properly using the specified relation (OR in this case).relation between meta queries based on your specific needs (e.g., AND vs. OR).Excluding Additional Posts:
$similar_to with any additional exclusions provided in $args['exclude'].array_unique to ensure that the exclusion list doesn't contain duplicate post IDs.Code Readability and Maintenance:
Debugging Exclusions:
If you find that $similar_to is still appearing in the results, you can add temporary debugging statements to verify that it's correctly added to post__not_in. For example:
error_log('Excluding post IDs: ' . implode(', ', $query_args['post__not_in']));
Check your server's error logs to see the output.
Performance Considerations:
LIKE comparisons in meta_query can impact performance, especially with large datasets. Consider optimizing your meta keys or using more efficient querying methods if performance becomes an issue.Testing:
$similar_to is not provided, when datosAlgoritmo is missing or malformed, and when there are overlapping exclusions.Security:
$_POST is properly validated and that the user has the necessary permissions to perform the query.Your approach to excluding the $similar_to post is on the right track. The revised function includes several enhancements to ensure robustness, security, and maintainability. By initializing arrays properly, sanitizing inputs, and carefully merging query parameters, you can prevent common issues and make the function more reliable.
Feel free to integrate these changes and adjust them based on your specific application context. If you encounter specific issues or have further questions, feel free to ask!
Not yet included in a published release.
function configuracionQueryArgs($args, $paged, $user_id, $current_user_id)
{
$identifier = $_POST['identifier'] ?? '';
$posts = isset($args['posts']) ? $args['posts'] : 10; // Default to 10 if not set
$similar_to = $args['similar_to'] ?? null;
$post_type = isset($args['post_type']) ? $args['post_type'] : 'post'; // Default to 'post'
// Initialize query arguments
$query_args = [
'post_type' => $post_type,
'posts_per_page' => $posts,
'paged' => $paged,
];
if ($post_type === 'social_post') {
$posts_personalizados = calcularFeedPersonalizado($current_user_id);
$post_ids = array_keys($posts_personalizados);
if ($paged == 1) {
$post_ids = array_slice($post_ids, 0, $posts);
}
$query_args['post__in'] = $post_ids;
$query_args['orderby'] = 'post__in';
if (!empty($identifier)) {
$query_args['meta_query'] = [
[
'key' => 'datosAlgoritmo',
'value' => $identifier,
'compare' => 'LIKE'
]
];
}
} else {
$query_args['orderby'] = 'date';
$query_args['order'] = 'DESC';
}
// Initialize post__not_in as an array if not already set
$query_args['post__not_in'] = isset($query_args['post__not_in']) ? $query_args['post__not_in'] : [];
// Handle similar posts
if ($similar_to) {
// Exclude the similar_to post
$query_args['post__not_in'][] = $similar_to;
// Get datosAlgoritmo meta
$datosAlgoritmo = get_post_meta($similar_to, 'datosAlgoritmo', true);
if ($datosAlgoritmo) {
$data = json_decode($datosAlgoritmo, true);
$meta_queries = [];
$relation = 'OR'; // Adjust as needed (AND/OR)
// BPM match
if (!empty($data['bpm'])) {
$meta_queries[] = [
'key' => 'datosAlgoritmo',
'value' => '"bpm":' . intval($data['bpm']),
'compare' => 'LIKE',
];
}
// Key match
if (!empty($data['key'])) {
$meta_queries[] = [
'key' => 'datosAlgoritmo',
'value' => '"key":"' . esc_sql($data['key']) . '"',
'compare' => 'LIKE',
];
}
// Scale match
if (!empty($data['scale'])) {
$meta_queries[] = [
'key' => 'datosAlgoritmo',
'value' => '"scale":"' . esc_sql($data['scale']) . '"',
'compare' => 'LIKE',
];
}
// Tags match
if (!empty($data['tags']) && is_array($data['tags'])) {
foreach ($data['tags'] as $tag) {
$meta_queries[] = [
'key' => 'datosAlgoritmo',
'value' => '"' . esc_sql($tag) . '"',
'compare' => 'LIKE',
];
}
}
if (!empty($meta_queries)) {
// Merge with existing meta_query if any
if (!empty($query_args['meta_query'])) {
$query_args['meta_query'][] = [
'relation' => $relation,
];
foreach ($meta_queries as $mq) {
$query_args['meta_query'][] = $mq;
}
} else {
$query_args['meta_query'] = [
'relation' => $relation,
...$meta_queries
];
}
}
}
}
// Handle additional exclusions
if (!empty($args['exclude']) && is_array($args['exclude'])) {
$query_args['post__not_in'] = array_merge($query_args['post__not_in'], $args['exclude']);
// Remove duplicates just in case
$query_args['post__not_in'] = array_unique($query_args['post__not_in']);
}
// Apply additional filters
$query_args = aplicarFiltros($query_args, $args, $user_id, $current_user_id);
return $query_args;
}