Toolset views

Problema con condicionales en Toolset Views

Problema

Cuando trabajamos con condicionales en Toolset Views, es común encontrarnos con problemas de sintaxis que impiden que nuestras condiciones funcionen correctamente. En este caso específico, estaba intentando aplicar un estilo diferente al último elemento de un bucle, comparando el índice actual ([wpv-loop-index]) con el número total de elementos ([wpv-post-count]).
El código original tenía estos problemas:

Uso incorrecto de operadores de comparación (le en lugar de lt para «menor que»)
Uso de comillas simples alrededor de los shortcodes de Toolset, lo que impedía su correcta evaluación

Solución

La solución consiste en:

[wpv-noautop]
[wpv-layout-start]
  [wpv-items-found]
    <!-- wpv-loop-start -->
	<wpv-loop>
		<!-- el nombre de membres és inferior al total -->
        [wpv-conditional if="( '[wpv-loop-index]' lt '[wpv-post-count]')"]
                [wpv-post-title], 
        [/wpv-conditional]
  
        <!-- el nombre de membres és inferior al total-->
        [wpv-conditional if="( '[wpv-loop-index]' eq '[wpv-post-count]')"]
                [wpv-post-title]
        [/wpv-conditional] 
	</wpv-loop>
	<!-- wpv-loop-end -->
  [/wpv-items-found]
[wpv-layout-end]

[/wpv-noautop]

Explicación de los shortcodes utilizados

[wpv-loop-index]

Este shortcode devuelve el número de iteración actual dentro del bucle de la vista. Comienza en 1 para el primer elemento y se incrementa en cada iteración. Es extremadamente útil cuando necesitas:

  • Aplicar estilos diferentes a elementos específicos (como el primero o el último)
  • Crear diseños basados en la posición (por ejemplo, alternar colores)
  • Implementar paginación manual o contadores personalizados

[wpv-post-count]

Este shortcode devuelve el número total de elementos (generalmente posts) que coinciden con los criterios de filtrado de la vista. Es útil para:

  • Saber cuántos elementos hay en total
  • Identificar el último elemento del bucle
  • Crear indicadores de progreso (Ej: «Mostrando 3 de 10»)
  • Aplicar lógica condicional basada en la cantidad total

Uso combinado

Cuando combinas ambos shortcodes con operadores condicionales, puedes crear diseños avanzados y personalizados según la posición relativa de cada elemento.

  • Operadores condicionales en Toolset
  • Para referencia, estos son los operadores condicionales más comunes en Toolset:
  • eq: igual a (equal)
  • neq: no igual a (not equal)
  • lt: menor que (less than)
  • le: menor o igual que (less than or equal)
  • gt: mayor que (greater than)
  • ge: mayor o igual que (greater than or equal)

Visto en Toolset

Problema con condicionales en Toolset Views Leer más »

Showing posts in calendar view based on start of the day

add_shortcode('ts_day_week_start', function($atts){
    $atts = shortcode_atts( array(
        'day' => 'Monday',
    ), $atts);
    $res = strtotime('last ' . $atts['day']);
    if(date('l') == $atts['day']){
        $res = strtotime('this ' . $atts['day']);
    }
    return $res;
});
 
 
add_shortcode('ts_day_week_end', function($atts){
    $atts = shortcode_atts( array(
        'day' => 'Monday',
    ), $atts);
    $res = strtotime('last ' . $atts['day']);
    if(date('l') == $atts['day']){
        $res = strtotime('this ' . $atts['day']);
    }
    $res = strtotime("tomorrow", $res) - 1;
    return $res;
});
[wpv-view name="schedule-view" cached="off" tsstart="[ts_day_week_start day='Friday']" tsend="[ts_day_week_end day='Friday']"]

Visto en Toolset

Showing posts in calendar view based on start of the day Leer más »

Toolset: Author frontend filtering with views and ajax

add_shortcode("list-of-authors", "list_of_authors");
function list_of_authors() {
  $out = '<option value="">All</option>';
  $users = get_users();
  foreach ($users as $user) {
    $selection = (isset($_GET['author-filter']) ? $_GET['author-filter']: '');
    $out .= '<option ' . selected($user->ID, $selection, false) . ' value="' . $user->ID . '">' . $user->display_name . '</a>';
  }
  return $out;
<select name="author-filter" class="js-wpv-filter-trigger">[list-of-authors]</select>

Visto en: https://toolset.com/forums/topic/author-frontend-filtering-with-views-and-ajax/

Toolset: Author frontend filtering with views and ajax Leer más »

Toolset: Búsquedas personalizadas con checkboxes y relación AND

add_filter( 'wpv_filter_query', 'wpv_atributs_serveis_negocis_wp', 99, 3 );
function wpv_atributs_serveis_negocis_wp( $query_args, $view_settings, $view_id ) {
    if ($view_id == 3900 && isset($_GET['wpv-wpcf-altres-serveis-del-negoci'])) {
         
        $my_args = array('relation' => 'AND');
        foreach($_GET['wpv-wpcf-altres-serveis-del-negoci'] as $offre){
            $my_args[] = array(
                'key'     => 'wpcf-altres-serveis-del-negoci',
                'value'   => $offre,
                'compare' => 'LIKE',
            );
        }
        $query_args['meta_query'][] = $my_args;
        foreach($query_args['meta_query'] as $k=>$v){
            if(isset($v['key']) && $v['key'] == 'wpcf-altres-serveis-del-negoci'){
                unset($query_args['meta_query'][$k]);
            }
        }
    }
    return $query_args;
}

Nota: wpv-wpcf-altres-serveis-del-negoci es el parámetro URL y wpcf-altres-serveis-del-negoci es el nombre del campo personalizado.

Visto en https://toolset.com/forums/topic/how-to-filter-by-more-than-one-checkbox/#post-631805

Toolset: Búsquedas personalizadas con checkboxes y relación AND Leer más »

Toolset: mostrar el rol de usuario en un bucle de una vista de usuarios

Add the following custom shortcode to your functions.php file:

function get_user_role_func( $atts )
{
  $a = shortcode_atts( array(
      'userid' => ''
  ), $atts );
  $userdata = get_user_by('ID', $a['userid']);
  $user_roles = $userdata->roles;
  $user_role = array_shift($user_roles);
  return $user_role;
}
add_shortcode( 'get_user_role', 'get_user_role_func' );

Then in your View, use the shortcode in a conditional like this:

[wpv-conditional if="( '[get_user_role userid='[wpv-user field='ID']']' eq 'editor' )"]
I am Editor
[/wpv-conditional]
[wpv-conditional if="( '[get_user_role userid='[wpv-user field='ID']']' eq 'administrator' )"]
I am Admin
[/wpv-conditional]

Register «get_user_role» in Toolset > Settings > Frontend Content > Third party shortcode arguments.

Visto en Toolset

Toolset: mostrar el rol de usuario en un bucle de una vista de usuarios Leer más »

Toolset: Mostrar relevancia de los resultados

add_shortcode( 'show_results_relevance', 'show_results_relevance_func');
function show_results_relevance_func($atts) {
    // get the searched terms for main ingredients
    $searched_recipe_main_ingredient = do_shortcode('[wpv-search-term param="wpv-main-ingredient"]');
    if(!empty($searched_recipe_main_ingredient))
    {
        $searched_recipe_main_ingredient_arr = explode(", ", $searched_recipe_main_ingredient);
        // count of searched main ingredients
        $searched_recipe_main_ingredient_count = count($searched_recipe_main_ingredient_arr);
  
        // get attached main ingredients for current post
        $attached_main_ingredients = do_shortcode("[wpv-post-taxonomy type='main-ingredient' format='name' separator=', ']");
  
        if(!empty($attached_main_ingredients))
        {   
            $attached_main_ingredients_arr = explode(", ", $attached_main_ingredients);
             
            // count of common ingredients which were searched and are also attached
            $matched_main_ingredients = count(array_intersect($searched_recipe_main_ingredient_arr,$attached_main_ingredients_arr));        
        }
        else
        {
            $matched_main_ingredients = 0;
        }
  
    }
    else
    {
        $searched_recipe_main_ingredient_count = 0;
        $matched_main_ingredients = 0;
    }
  
 
 
 
    return ($matched_main_ingredients/$searched_recipe_main_ingredient_count*100);
 
}

Visto en Toolset

Toolset: Mostrar relevancia de los resultados Leer más »

View select all in filter and live search

<input type="checkbox" id="selecctall_neighborhood" name="selecctall_neighborhood" value="selecctall_neighborhood" class="js-wpv-filter-trigger" [wpv-conditional if=" ('[wpv-search-term param="selecctall_neighborhood"]' eq 'selecctall_neighborhood') "]checked="checked"[/wpv-conditional] />
jQuery( document ).on( 'js_event_wpv_parametric_search_results_updated', function( event, data ) {
    /**
    * data.view_unique_id (string) The View unique ID hash
    * data.layout (object) The jQuery object for the View layout wrapper
    */
    $('#selecctall_neighborhood').click(function(event) {  //on click 
        if(this.checked) { // check select status
            $('#check_neighborhood .js-wpv-filter-trigger').each(function() { //loop through each checkbox
                this.checked = true;  //select all checkboxes with class "checkbox_neighborhood"               
            });
        }else{
            $('#check_neighborhood .js-wpv-filter-trigger').each(function() { //loop through each checkbox
                this.checked = false; //deselect all checkboxes with class "checkbox_neighborhood"                       
            });         
        }
    });
});

Visto en Toolset

View select all in filter and live search Leer más »

Primera letra de cada custom post type

[wpv-layout-start]
    [wpv-items-found]
    <a href="[current_url]">All</a>
    <!-- wpv-loop-start -->
        <wpv-loop>
            <a href="?wpvalphabet=[wpv-taxonomy-title]">[wpv-taxonomy-title]</a>
        </wpv-loop>
    <!-- wpv-loop-end -->
    [/wpv-items-found]
    [wpv-no-items-found]
        <strong>[wpml-string context="wpv-views"]No items found[/wpml-string]</strong>
    [/wpv-no-items-found]
[wpv-layout-end]
add_shortcode( 'current_url', function(){
    
    $request = $_SERVER['HTTP_HOST'].strtok($_SERVER["REQUEST_URI"],'?');
    $protocol = 'http://';
    
    if ( isset($_SERVER['HTTPS']) ) {
        $protocol = 'https://';
    }
    
    return $protocol . $request;
} );
wpv-layout-start]
[wpv-view name="alphabet-terms"]
[wpv-items-found]
<!-- wpv-loop-start -->
        <wpv-loop>
            <h3>[wpv-post-link]</h3>
        </wpv-loop>
    <!-- wpv-loop-end -->
    [/wpv-items-found]
    [wpv-no-items-found]
        <strong>[wpml-string context="wpv-views"]No items found[/wpml-string]</strong>
    [/wpv-no-items-found]
[wpv-layout-end]
add_filter('wpv_filter_query', 'func_filter_by_title', 10, 2);
function func_filter_by_title($query, $setting) {
  
global $wpdb;
      
if($setting['view_id'] == 9999) {
          
        if(isset($_GET['wpvalphabet']) and $_GET['wpvalphabet']!='' ){
              
              
            $first_char = $_GET['wpvalphabet'];
            $postids = $wpdb->get_col($wpdb->prepare("SELECT      ID
                                                        FROM        $wpdb->posts
                                                        WHERE       SUBSTR($wpdb->posts.post_title,1,1) = %s
                                                        AND post_type = '".$query['post_type'][0]."'
                                                        AND post_status = 'publish'
                                                        ORDER BY    $wpdb->posts.post_title",$first_char)); 
                                                          
                  $query['post__in'] = $postids;
                  }
  }
return 

https://toolset.com/forums/topic/show-hidden-links/#post-1612419

Primera letra de cada custom post type Leer más »

Scroll al inicio