¿Cómo dar a los enlaces paginados un título personalizado?

12

He dividido el contenido de mi publicación en varias páginas utilizando el código <! - nextpage -> . Quiero dar a mis enlaces paginados su propio título en lugar del habitual 1,2,3. ¿Cómo puedo hacer esto? en este documento enlace solo se menciona el método para agregar un sufijo o prefijo. Solo quiero dar a cada número paginado su propio título personalizado

    
pregunta Ruriko 15.09.2015 - 02:38

2 respuestas

17

Aquí hay una forma de admitir los títulos de paginación del formulario:

<!--nextpage(.*?)?--> 

de forma similar, ya que el núcleo admite <!--more(.*?)?--> .

Aquí hay un ejemplo:

<!--nextpage Planets -->
Let's talk about the Planets
<!--nextpage Mercury -->
Exotic Mercury
<!--nextpage Venus-->
Beautiful Venus
<!--nextpage Earth -->
Our Blue Earth
<!--nextpage Mars -->
The Red Planet

con la salida similar a:

EstoseprobóeneltemaTwentySixteen,dondetuvequeajustarunpocoelpaddingywidth:

.page-linksa,.page-links>span{width:auto;padding:05px;}

Complementodedemostración

Aquíhayuncomplementodedemostraciónqueutilizalosfiltroscontent_pagination,wp_link_pages_link,pre_handle_404ywp_link_pages_argsparaapoyarestaextensióndelmarcadornextpage(PHP5.4+):

<?php/***PluginName:ContentPaginationTitles*Description:Supportfor&lt;!--nextpage(.*?)?--&gt;inthepostcontent*Version:1.0.1*PluginURI:http://wordpress.stackexchange.com/a/227022/26350*/namespaceWPSE\Question202709;add_action('init',function(){$main=newMain;$main->init();});classMain{private$pagination_titles;publicfunctioninit(){add_filter('pre_handle_404',[$this,'pre_handle_404'],10,2);add_filter('content_pagination',[$this,'content_pagination'],-1,2);add_filter('wp_link_pages_link',[$this,'wp_link_pages_link'],10,2);add_filter('wp_link_pages_args',[$this,'wp_link_pages_args'],PHP_INT_MAX);}publicfunctioncontent_pagination($pages,$post){//Emptycontentpaginationtitlesforeachrun$this->pagination_titles=[];//Nothingtodoifthepostcontentdoesn'tcontainpaginationtitlesif(false===stripos($post->post_content,'<!--nextpage'))return$pages;//Collectpaginationtitlespreg_match_all('/<!--nextpage(.*?)?-->/i',$post->post_content,$matches);if(isset($matches[1]))$this->pagination_titles=$matches[1];//Override$pagesaccordingtoournewextendednextpagesupport$pages=preg_split('/<!--nextpage(.*?)?-->/i',$post->post_content);//nextpagemarkeratthetopif(isset($pages[0])&&''==trim($pages[0])){//removetheemptypagearray_shift($pages);}//nextpagemarkernotatthetopelse{//addthefirstnumericpaginationtitlearray_unshift($this->pagination_titles,'1');}return$pages;}publicfunctionwp_link_pages_link($link,$i){if(!empty($this->pagination_titles)){$from='{{TITLE}}';$to=!empty($this->pagination_titles[$i-1])?$this->pagination_titles[$i-1]:$i;$link=str_replace($from,$to,$link);}return$link;}publicfunctionwp_link_pages_args($params){if(!empty($this->pagination_titles)){$params['next_or_number']='number';$params['pagelink']=str_replace('%','{{TITLE}}',$params['pagelink']);}return$params;}/***BasedonthenextpagecheckinWP::handle_404()*/publicfunctionpre_handle_404($bool,\WP_Query$q){global$wp;if($q->posts&&is_singular()){if($q->postinstanceof\WP_Post)$p=clone$q->post;//checkforpagedcontentthatexceedsthemaxnumberofpages$next='<!--nextpage';if($p&&false!==stripos($p->post_content,$next)&&!empty($wp->query_vars['page'])){$page=trim($wp->query_vars['page'],'/');$success=(int)$page<=(substr_count($p->post_content,$next)+1);if($success){status_header(200);$bool=true;}}}return$bool;}}//endclass

Instalación:creaelarchivo/wp-content/plugins/content-pagination-titles/content-pagination-titles.phpyactivaelcomplemento.Siempreesunabuenaidearealizarunacopiadeseguridadantesdeprobarcualquiercomplemento.

Sifaltaelmarcadorsuperiornextpage,elprimertítulodepaginaciónesnumérico.

Tambiénsifaltauntítulodepaginacióndecontenido,esdecir,<!--nextpage-->,entoncesseránumérico,talcomoseesperaba.

PrimeromeolvidédelerrornextpageenlaclaseWP,queaparecesimodificamoselnúmerodepáginasatravésdelfiltrocontent_pagination[email protected]íen # 35562 .

Intentamos superar eso en nuestro complemento de demostración con una devolución de llamada pre_handle_404 filter, basado en la comprobación de clase WP aquí , donde verificamos <!--nextpage en lugar de <!--nextpage--> .

Pruebas

Aquí hay algunas pruebas adicionales:

Prueba # 1

<!--nextpage-->
Let's talk about the Planets
<!--nextpage-->
Exotic Mercury
<!--nextpage-->
Beautiful Venus
<!--nextpage-->
Our Blue Earth
<!--nextpage-->
The Red Planet

Salida para 1 seleccionada:

comoseesperaba.

Prueba#2

Let'stalkaboutthePlanets<!--nextpage-->ExoticMercury<!--nextpage-->BeautifulVenus<!--nextpage-->OurBlueEarth<!--nextpage-->TheRedPlanet

Salidapara5seleccionada:

comoseesperaba.

Prueba#3

<!--nextpage-->Let'stalkaboutthePlanets<!--nextpageMercury-->ExoticMercury<!--nextpage-->BeautifulVenus<!--nextpageEarth-->OurBlueEarth<!--nextpageMars-->TheRedPlanet

Salidapara3seleccionada:

comoseesperaba.

Prueba#4

Let'stalkaboutthePlanets<!--nextpageMercury-->ExoticMercury<!--nextpageVenus-->BeautifulVenus<!--nextpageEarth-->OurBlueEarth<!--nextpageMars-->TheRedPlanet

SalidaconTierraseleccionada:

como se esperaba.

Alternativas

Otra forma sería modificarlo para admitir los títulos de paginación que se agregarán con:

<!--pt Earth-->

También podría ser útil admitir un solo comentario para todos los títulos de paginación ( pts ):

<!--pts Planets|Mercury|Venus|Earth|Mars -->

o quizás a través de campos personalizados?

    
respondido por el birgire 18.05.2016 - 12:39
5

Puede usar el filtro wp_link_pages_link

Primero pase nuestro marcador de posición de cadena personalizado (puede ser lo que quiera, excepto la cadena que contiene % , solo por ahora estoy usando #custom_title# ).

wp_link_pages( array( 'pagelink' => '#custom_title#' ) );

Luego agrega nuestro filtro en functions.php . En la función de devolución de llamada, haga una serie de títulos, luego verifique el número de la página actual y reemplace #custom_title# con el valor correspondiente al número de la página actual.

Ejemplo: -

add_filter('wp_link_pages_link', 'wp_link_pages_link_custom_title', 10, 2);
/**
 * Replace placeholder with custom titles
 * @param string $link Page link HTML
 * @param int $i Current page number
 * @return string $link Page link HTML
 */
function wp_link_pages_link_custom_title($link, $i) {

    //Define array of custom titles
    $custom_titles = array(
        __('Custom title A', 'text-domain'),
        __('Custom title B', 'text-domain'),
        __('Custom title C', 'text-domain'),
    );

    //Default title when title is not set in array
    $default_title = __('Page', 'text-domain') . ' ' . $i; 

    $i--; //Decrease the value by 1 because our array start with 0

    if (isset($custom_titles[$i])) { //Check if title exist in array if yes then replace it
        $link = str_replace('#custom_title#', $custom_titles[$i], $link);
    } else { //Replace with default title
        $link = str_replace('#custom_title#', $default_title, $link);
    }

    return $link;
}
    
respondido por el Sumit 18.05.2016 - 11:37

Lea otras preguntas en las etiquetas