jQuery: implementare la funzione the_excerpt di WordPress

jQuery: implementare la funzione the_excerpt di WordPress

La funzione di WordPress the_excerpt() restituisce il sommario di un post. In jQuery possiamo estrarre una porzione della stringa restituita da un nodo di testo di un elemento e aggiungervi dei caratteri di sospensione per simulare il risultato ottenuto dalla funzione originale di WordPress. Vediamo come fare.

Implementeremo il seguente plugin:


(function($) {

    $.fn.the_excerpt = function(options) {

        var that = this;

        options = $.extend({
            length: 160,
            ellipsis: '...'
        }, options);

        var theExcerpt = function(str, length) {

            var newStr = str;
            var words = str.split('', length + 1);

            if (words.length > length) {
                words.pop();
                words.push(options.ellipsis);
                newStr = words.join('');
            }

            return newStr;
        };

        return that.each(function() {

            var text = $(that).text();
            var excerpt = theExcerpt(text, options.length);

            $(that).text(excerpt);

        });


    }



})(jQuery);

Il plugin accetta come opzioni la lunghezza massima della stringa da restituire e i caratteri di sospensione da inserire alla fine del testo. Ecco un esempio d'uso:


$('#run').click(function() {

    $('#test').the_excerpt();
    
});

Potete visionare l'esempio finale in questa pagina.

Torna su