我有一组页面,它们使用路径信息来创建相关新闻文章的视图。
例:
mysite.com/city-service
mysite.com/country-service
etc我有一个现有的视图,它使用上下文过滤器提取URL的相关部分,然后查找带有组织标记的相关新闻文章,该标记映射到每个服务。
这很好,但是我被要求将视图更改为以下行为:
我不允许为工作人员从根本上重新设计页面或工作流程--比如手动标记所有新闻文章--所以我唯一能得到分类术语名称的地方是url。
如何根据从页面url获取参数的分类法术语名称对视图结果进行排序?
发布于 2022-11-07 08:23:11
要实现这一点,您需要使用自定义模块中的hook_views_query_alter修改视图查询。读取请求的URL并获取相关的分类法术语。然后,您可以根据需要调整查询。在这里也可以找到类似的答案:如何对同一视图中的不同列进行排序?
下面是一个示例:
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\views\ViewExecutable;
function MYMODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
// Determine view by id and current display.
if ($view->id() == 'content_recent' && $view->current_display == 'default') {
// Get the requested path.
$request = \Drupal::request();
$path = $request->getPathInfo();
// Use some logic to get the term for the current path.
// @see https://drupal.stackexchange.com/a/266084/15055
$tid = FALSE;
if ($path == 'example') {
$tid = 9;
}
// If the URL belongs to a term, we change the order.
if ($tid) {
// You may need to add a relationship to the taxonomy terms,
// if your view is not already doing this or add it in the Views UI.
$sql = "CASE
WHEN taxonomy_term_field_data_node_field_data.tid = $tid THEN 0
ELSE 1
END";
// Add the sql formula for sorting.
$query->addField(NULL, $sql, 'related_taxonomy_term');
// We first sort by the related term and than by the views settings,
// which should for example be the changed date descending.
$query->orderby = array_merge([[
'field' => 'related_taxonomy_term',
'direction' => 'ASC',
]], $query->orderby);
}
}
}https://drupal.stackexchange.com/questions/313487
复制相似问题