function configuracionQueryArgs($args, $paged, $userid, $currentuserid) { global…
- User
function configuracionQueryArgs(paged, current_user_id) { global FALLBACK_USER_ID)) { $FALLBACK_USER_ID = 44; }
- Assistant
function configuracionQueryArgs(paged, current_user_id) { global FALLBACK_USER_ID)) { $FALLBACK_USER_ID = 44; }
$is_authenticated = $current_user_id && $current_user_id != 0;
$is_admin = current_user_can('administrator');
if (!$is_authenticated) {
$current_user_id = $FALLBACK_USER_ID;
}
$identifier = $_POST['identifier'] ?? '';
$posts = $args['posts'];
$similar_to = $args['similar_to'] ?? null;
$filtroTiempo = (int)get_user_meta($current_user_id, 'filtroTiempo', true);
$query_args = construirQueryArgs($args, $paged, $current_user_id, $identifier, $is_admin, $posts, $filtroTiempo, $similar_to);
$query_args = aplicarFiltrosUsuario($query_args, $current_user_id);
$query_args = aplicarFiltroGlobal($query_args, $args, $current_user_id);
return $query_args;
}
function construirQueryArgs(paged, identifier, posts, similar_to) { global query_args = [ 'post_type' => posts, 'paged' => $paged, 'ignore_sticky_posts' => true, 'suppress_filters' => false, ];
postLog("Iniciando construirQueryArgs con filtroTiempo: $filtroTiempo");
// Aplicar filtro de identificador
if (!empty($identifier)) {
$query_args = filtrarIdentifier($identifier, $query_args);
}
// Aplicar ordenamiento
if ($args['post_type'] === 'social_post') {
$query_args = ordenamientoQuery($query_args, $filtroTiempo, $current_user_id, $identifier, $similar_to, $paged, $is_admin, $posts);
}
postLog("Query args finales: " . print_r($query_args, true));
return $query_args;
}
function filtrarIdentifier(query_args) { global $wpdb;
// Normalizar el término de búsqueda
$identifier = strtolower(trim($identifier));
// Remover 's' final si existe (para manejar plurales)
$terms = explode(' ', $identifier);
$normalized_terms = array();
foreach ($terms as $term) {
$term = trim($term);
if (empty($term)) continue;
// Agregar tanto la versión singular como plural
$normalized_terms[] = $term;
if (substr($term, -1) === 's') {
$normalized_terms[] = substr($term, 0, -1); // Versión singular
} else {
$normalized_terms[] = $term . 's'; // Versión plural
}
}
$normalized_terms = array_unique($normalized_terms);
$query_args['s'] = $identifier;
add_filter('posts_search', function ($search, $wp_query) use ($normalized_terms, $wpdb) {
if (empty($normalized_terms)) {
return $search;
}
$search = '';
$search_conditions = array();
// Construir condición OR para cada término y sus variaciones
$term_conditions = array();
foreach ($normalized_terms as $term) {
$like_term = '%' . $wpdb->esc_like($term) . '%';
$term_conditions[] = $wpdb->prepare("
{$wpdb->posts}.post_title LIKE %s OR
{$wpdb->posts}.post_content LIKE %s OR
EXISTS (
SELECT 1 FROM {$wpdb->postmeta}
WHERE {$wpdb->postmeta}.post_id = {$wpdb->posts}.ID
AND {$wpdb->postmeta}.meta_key = 'datosAlgoritmo'
AND {$wpdb->postmeta}.meta_value LIKE %s
)
", $like_term, $like_term, $like_term);
}
if (!empty($term_conditions)) {
$search .= ' AND (' . implode(' OR ', $term_conditions) . ')';
}
return $search;
}, 10, 2);
return $query_args;
}
function ordenamientoQuery(filtroTiempo, identifier, paged, posts) { global likes_table = $wpdb->prefix . 'post_likes';
switch ($filtroTiempo) {
case 1: // Posts recientes
$query_args['orderby'] = 'date';
$query_args['order'] = 'DESC';
postLog("Caso 1: Ordenando por fecha reciente");
break;
case 2: // Top semanal
case 3: // Top mensual
$interval = ($filtroTiempo === 2) ? '1 WEEK' : '1 MONTH';
postLog("Caso $filtroTiempo: Usando intervalo de $interval");
$sql = "
SELECT p.ID,
COUNT(pl.post_id) as like_count
FROM {$wpdb->posts} p
LEFT JOIN {$likes_table} pl ON p.ID = pl.post_id
WHERE p.post_type = 'social_post'
AND p.post_status = 'publish'
AND p.post_date >= DATE_SUB(NOW(), INTERVAL $interval)
AND pl.like_date >= DATE_SUB(NOW(), INTERVAL $interval)
GROUP BY p.ID
HAVING like_count > 0
ORDER BY like_count DESC, p.post_date DESC
";
postLog("SQL Query: " . $sql);
$posts_with_likes = $wpdb->get_results($sql, ARRAY_A);
postLog("Resultados encontrados: " . count($posts_with_likes));
if (!empty($posts_with_likes)) {
$post_ids = wp_list_pluck($posts_with_likes, 'ID');
if (!empty($post_ids)) {
$query_args['post__in'] = $post_ids;
$query_args['orderby'] = 'post__in';
}
postLog("IDs de posts para esta página: " . implode(', ', $post_ids));
} else {
postLog("No se encontraron posts con likes en el período especificado");
$query_args['orderby'] = 'date';
$query_args['order'] = 'DESC';
}
break;
default:
postLog("Caso default: Obteniendo feed personalizado");
En el caso default se supone que esto calcula los post mas relavantes para el usuario (lo hace internamente, antes funcionaba pero parece que algo se daño y simplemente regresa los post mas recientes)
obtenerFeedPersonalizado($current_user_id, $identifier, $similar_to, $paged, $is_admin, $posts);
break;
}
return $query_args;
}
function obtenerFeedPersonalizado(identifier, paged, posts_per_page) { $post_not_in = [];
if ($similar_to) {
$post_not_in[] = $similar_to;
$cache_suffix = "_similar_" . $similar_to;
} else {
$cache_suffix = "";
}
$transient_key = $current_user_id == 44
? "feed_personalizado_anonymous_{$identifier}{$cache_suffix}"
: "feed_personalizado_user_{$current_user_id}_{$identifier}{$cache_suffix}";
$use_cache = !$is_admin;
$cached_data = $use_cache ? get_transient($transient_key) : false;
if ($cached_data) {
$posts_personalizados = $cached_data['posts'];
} else {
if ($paged === 1) {
$posts_personalizados = calcularFeedPersonalizado($current_user_id, $identifier, $similar_to);
} else {
$posts_personalizados = get_option($transient_key . '_backup', []);
if (empty($posts_personalizados)) {
$posts_personalizados = calcularFeedPersonalizado($current_user_id, $identifier, $similar_to);
}
}
if ($use_cache) {
$cache_data = ['posts' => $posts_personalizados, 'timestamp' => time()];
$cache_time = $similar_to ? 3600 : 86400;
set_transient($transient_key, $cache_data, $cache_time);
update_option($transient_key . '_backup', $posts_personalizados);
}
}
$post_ids = array_keys($posts_personalizados);
if ($similar_to) {
$post_ids = array_filter($post_ids, function ($post_id) use ($similar_to) {
return $post_id != $similar_to;
});
}
$post_ids = array_keys($posts_personalizados);
if ($similar_to) {
$post_ids = array_filter($post_ids, function ($post_id) use ($similar_to) {
return $post_id != $similar_to;
});
}
$post_ids = array_unique($post_ids);
return [
'post_ids' => $post_ids,
'post_not_in' => [],
];
}
function calcularFeedPersonalizado(identifier = '', similar_to = null) { // Validar que el userId sea válido if (empty(userId) || !is_numeric(userId)) { error_log("Usuario ID inválido Feed: " . print_r(userId, true)); return []; }
$datos = obtenerDatosFeedConCache($userId);
if (empty($datos)) {
error_log("Datos vacíos para usuario ID: " . $userId);
return [];
}
// Obtener y validar datos del usuario
$usuario = get_userdata($userId);
if (!$usuario || !is_object($usuario)) {
error_log("No se pudo obtener datos del usuario ID: " . $userId);
return [];
}
// Validar roles del usuario
$esAdmin = false;
if (isset($usuario->roles) && is_array($usuario->roles)) {
$esAdmin = in_array('administrator', $usuario->roles);
} else {
$roles = array_map('strtolower', (array) $usuario->roles);
$esAdmin = in_array('administrator', $roles);
}
// Obtener y validar vistas de posts
$vistas_posts_processed = obtenerYProcesarVistasPosts($userId);
if ($vistas_posts_processed === false) {
error_log("Error al procesar vistas de posts para usuario ID: " . $userId);
return [];
}
$posts_personalizados = [];
$resumenPuntos = [];
// Validar que author_results sea un array
if (!isset($datos['author_results']) || !is_array($datos['author_results'])) {
error_log("author_results no es válido para usuario ID: " . $userId);
return [];
}
$current_timestamp = current_time('timestamp');
foreach ($datos['author_results'] as $post_id => $post_data) {
try {
$puntosFinal = calcularPuntosPost(
$post_id,
$post_data,
$datos,
$esAdmin,
$vistas_posts_processed,
$identifier,
$similar_to,
$current_timestamp,
$userId
);
if (is_numeric($puntosFinal)) {
$posts_personalizados[$post_id] = $puntosFinal;
$resumenPuntos[$post_id] = round($puntosFinal, 2);
}
} catch (Exception $e) {
error_log("Error al calcular puntos para post ID {$post_id}: " . $e->getMessage());
continue;
}
}
if (empty($posts_personalizados)) {
error_log("No se generaron posts personalizados para usuario ID: " . $userId);
return [];
}
arsort($posts_personalizados);
arsort($resumenPuntos);
return $posts_personalizados;
}
It looks like you're encountering an issue where your personalized feed is not functioning as expected—it’s returning the most recent posts instead of personalized ones. After reviewing your code, there are a couple of issues that might be causing this problem:
Uncommented Text in Code (Syntax Error):
In your ordenamientoQuery function, within the default case, you have a line of text that's not properly commented out. This will cause a syntax error and prevent your code from executing correctly.
// This line is causing a syntax error
En el caso default se supone que esto calcula los post mas relavantes para el usuario (lo hace internamente, antes funcionaba pero parece que algo se daño y simplemente regresa los post mas recientes)
Solution: Comment out this line or remove it entirely.
// En el caso default se supone que esto calcula los posts más relevantes para el usuario...
Ignoring the Result of obtenerFeedPersonalizado:
In the same ordenamientoQuery function, you're calling obtenerFeedPersonalizado, but you're not using its return value to modify $query_args. As a result, $query_args doesn't include the personalized post IDs, and WordPress defaults to fetching the most recent posts.
Solution: Capture the return value of obtenerFeedPersonalizado and update $query_args accordingly.
Here's how you can modify your ordenamientoQuery function:
function ordenamientoQuery($query_args, $filtroTiempo, $current_user_id, $identifier, $similar_to, $paged, $is_admin, $posts)
{
global $wpdb;
$likes_table = $wpdb->prefix . 'post_likes';
switch ($filtroTiempo) {
case 1: // Posts recientes
$query_args['orderby'] = 'date';
$query_args['order'] = 'DESC';
postLog("Caso 1: Ordenando por fecha reciente");
break;
case 2: // Top semanal
case 3: // Top mensual
// Existing code for cases 2 and 3...
break;
default:
postLog("Caso default: Obteniendo feed personalizado");
// Remove or comment out the problematic line
// En el caso default se supone que esto calcula los posts más relevantes para el usuario...
// Get personalized feed
$feed_personalizado = obtenerFeedPersonalizado($current_user_id, $identifier, $similar_to, $paged, $is_admin, $posts);
// Check if we have personalized posts
if (!empty($feed_personalizado['post_ids'])) {
$query_args['post__in'] = $feed_personalizado['post_ids'];
$query_args['orderby'] = 'post__in';
// Handle pagination by slicing the post IDs
$offset = ($paged - 1) * $posts;
$query_args['post__in'] = array_slice($feed_personalizado['post_ids'], $offset, $posts);
postLog("Using personalized post IDs: " . implode(', ', $query_args['post__in']));
} else {
// Fallback to default ordering
$query_args['orderby'] = 'date';
$query_args['order'] = 'DESC';
postLog("No personalized posts found; ordering by date DESC");
}
break;
}
return $query_args;
}
Explanation:
obtenerFeedPersonalizado in a variable ($feed_personalizado).post_ids are present in the personalized feed, update $query_args with these IDs and set the orderby parameter to 'post__in'.post_ids array appropriately.Ensure Consistency in Returned Data:
In obtenerFeedPersonalizado, ensure that you're consistently returning the expected structure, even if the feed is empty.
function obtenerFeedPersonalizado($current_user_id, $identifier, $similar_to, $paged, $is_admin, $posts_per_page)
{
// Existing code...
// Always return an array with 'post_ids' and 'post_not_in'
return [
'post_ids' => $post_ids ?? [],
'post_not_in' => $post_not_in ?? [],
];
}
Verify Data in calcularFeedPersonalizado:
Make sure that calcularFeedPersonalizado is returning the correct post IDs based on your personalization logic.
error_log or postLog.Additional Debugging Steps:
postLog or error_log to log intermediate values and ensure that your data is flowing correctly through the functions.// Clear transient for testing
delete_transient($transient_key);
calcularFeedPersonalizado, ensure that the user data ($usuario) and roles are correctly retrieved.Test the Personalization Logic Independently:
If possible, isolate the personalization logic in calcularFeedPersonalizado and test it independently to ensure it returns the expected results.
Sample Updated calcularFeedPersonalizado:
Here's a brief outline to ensure it returns post IDs correctly:
function calcularFeedPersonalizado($userId, $identifier = '', $similar_to = null)
{
// Existing validation code...
// Assuming you have personalized scores for each post
$posts_personalizados = [];
// Example: Fetch posts and assign random scores (replace with actual logic)
$args = [
'post_type' => 'social_post',
'posts_per_page' => -1,
'fields' => 'ids',
];
$all_posts = get_posts($args);
foreach ($all_posts as $post_id) {
// Your logic to calculate points for each post
$puntosFinal = rand(1, 100); // Replace with actual scoring logic
$posts_personalizados[$post_id] = $puntosFinal;
}
if (empty($posts_personalizados)) {
error_log("No personalized posts generated for user ID: " . $userId);
return [];
}
// Sort posts by score in descending order
arsort($posts_personalizados);
// Return only the post IDs, preserving order
return array_keys($posts_personalizados);
}
Note: Replace the placeholder logic with your actual personalization algorithm.
Ensure Pagination Works Correctly: Since you're implementing pagination, make sure that you're retrieving the correct subset of posts for each page.
Example:
// In ordenamientoQuery after getting personalized posts
$offset = ($paged - 1) * $posts;
$paged_post_ids = array_slice($feed_personalizado['post_ids'], $offset, $posts);
$query_args['post__in'] = $paged_post_ids;
Fallback for Empty Personalized Feed: If personalization doesn't return any posts (which can happen), ensure your code gracefully falls back to a default set of posts.
if (empty($feed_personalizado['post_ids'])) {
postLog("No personalized posts found; falling back to default posts");
// Fallback query arguments
$query_args['orderby'] = 'date';
$query_args['order'] = 'DESC';
}
Testing:
Summary: The main issues were an uncommented line causing a syntax error and not properly utilizing the personalized post IDs in your query arguments. By addressing these issues and ensuring that your functions return and use data as expected, your personalized feed should start working correctly again.
Not yet included in a published release.