当帖子有多个类别时,是否将一个类别呼应为标题?

时间:2015-06-18 作者:Nate

UPDATED QUESTION to be CLEARER

以下是我的情况:

Wordpress顶部导航有几个菜单项,可以跳转到特定类别中的一组帖子。例如,如果单击“necklaces”,您将在necklaces部分找到自己。您可以单击“下一步”或“上一步”按钮,进入下一条项链贴子。

在页面顶部,有一个H2标记,通过获取其类别名称来显示标题:

<?php
    $category = get_the_category();
    echo $category[0]->cat_name;
?>
问题是,所有这些帖子都列在多个类别下。以上代码仅获取第一个类别。如果一篇文章被列在“项链”和“吊坠”类别下,那么它将在其中一个类别中显示错误的标题。

因此,我需要让标题根据用户目前所处的实际类别显示正确的类别。当前,当您单击“下一步”或“上一步”时,标题将根据该特定帖子的第一个类别随机更改。

有几十个类别。他们都是单身。php模板。我正试图改变单曲的标题。php模板页面不是类别。php

3 个回复
最合适的回答,由SO网友:Pieter Goosen 整理而成

为了做到这一点,你需要知道单个帖子是从哪里引荐的,以及引荐人是否有效。其次,我们需要调整单个帖子之间的分页,以便我们在单个帖子之间传递推荐人。

引用器的问题是,它们是由用户端设置和控制的。可以禁用或阻止引用者(就像用户通过代理访问站点一样)。出于兴趣,下面是一个非常有趣的问题的答案,在什么情况下http引用将是空的this post on SO

当最终用户

在浏览器地址栏中输入网站URL

  • 通过浏览器维护的书签访问了该网站
  • 作为窗口/选项卡中的第一页访问了该网站
  • 从https URL切换到其他https URL
  • 安装了安全软件(防病毒/防火墙等),该软件可从所有请求中删除推荐人
  • 背后有一个代理,该代理从所有请求中删除推荐人curl) 不设置引用者标题(searchbots!)
  • 您还需要阅读其他答案以获得更多的见解

    我遇到了类似的问题,正在寻找一种更可靠的方法来设置和传递推荐人,这导致了this question 还有一个很棒的answer by @gmazzap

    因此,您的解决方案将基于类似的内容。我们将在URL中添加一个特殊参数,作为推荐人(我假设您的帖子来自内置帖子类型post 和分类学category

    识别我们的分类页面,并通过post_link 滤器此推荐人将保留类别id。您可以使用类别名称,但这可能会在您的URL中变得非常混乱。选择全由你决定。

    add_filter(\'post_link\', function( $permalink ) // Change to post_type_link for custom post type posts
    {
        if (      is_category() // Change to is_tax() for custom taxonomy pages
             && ( $cat = get_queried_object() ) 
        ) {
            $permalink = esc_url( add_query_arg( array( \'ref\' => $cat->term_id ), $permalink ) );
        }
        return $permalink;
    });
    
    如果您单击分类页面上的帖子链接,这将在您的单个帖子页面上为您提供如下URL

    http://example.com/wordpress/post-name?ref=1
    
    我们必须有一种方法来读取和使用URL中的信息,以使其有用。为此,我们必须在查询参数中添加ref 这样Wordpress就可以读了

    add_filter( \'query_vars\', function ( $vars ) 
    {
        $vars[] = \'ref\';
        return $vars;
    });
    
    您现在需要做的就是检查单个帖子是否是引用的帖子,从URL中获取值,并使用该信息显示正确的类别名称(NOTE: 这段代码进入您的single.php

    $referrer = filter_input( INPUT_GET, \'ref\', FILTER_VALIDATE_INT ); // This validate and checks if our referrer "ref" is set
    if ( $referrer ) {
        $category = get_category( $referrer );
        echo \'<h2>\' . $category->name . \'</h2>\';
    }
    
    以上只是一个粗略的草案,你可以做些什么来完成这项工作,它只是给你一个工作的基础。您可以根据需要对其进行调整和修改。

    在你的单个页面上,你还需要找到你的推荐人,并将其传递给你的下一个和上一个帖子链接,以便在帖子之间保持此功能。我已经写了一个基于此分页的答案,虽然它相当庞大,可以使用一些清理。现在,我已经处理了一些部件,还有一些部件您可能永远都不需要,您可以将其移除。您可以根据需要对其进行修改和调整。

    我正忙着用一些额外的功能重写完整的分页函数(使用更好、更干净的php功能),这些类都完成了,只是最后一部分将所有东西都放到函数中,这让我感到噩梦,老实说,我已经有一段时间没有回去做这个项目了,因为我晚上真的没有太多时间。何时完工仍然是个谜。但是,我在这个具体答案中给出的想法和代码应该对您有用。您可以查看我的答案和参考分页功能here

    编辑我很快写了一个小插件,它包含了推荐人和新的分页链接,可以将推荐人带到多个单独的帖子中。此分页链接还将在来自推荐人的单个帖子之间分页

    这意味着,如果从category B, 这篇文章分为三类,category A, category Bcategory C, 下一个和上一个相邻立柱将来自category B. 如果您转到任一帖子,则单击的单个帖子中的相邻帖子也将来自category B

    我已经对代码进行了注释,因此您应该能够更好地遵循它,并根据需要对其进行调整和修改。只需将此代码复制并粘贴到插件文件中,然后将其激活即可。或者,复制代码(当然没有插件头),并将其按原样粘贴到functions.php (NOTE: 这只适用于内置分类法category 以及内置post类型post. 您应该根据帖子类型和自定义分类法根据需要对其进行相应的修改

    <?php
    /*
     * Plugin Name: Category referred posts
     * URI: https://wordpress.stackexchange.com/a/192018/31545
     * Description: Add referrer links to single posts and pagination if single posts was referred from a category page
     * Version: 1.0
     * Author: Pieter Goosen
     */
    
    /*
     * Add our custom query vars so Wordpress can read it
     */
    add_filter( \'query_vars\', function ( $vars ) 
    {
        $vars[] = \'ref\';
        return $vars;
    });
    
    /* 
     * Add our referrer to single post links if we are on a category page
     */
    add_filter(\'post_link\', function( $permalink ) // Change to post_type_link for custom post type posts
    {
        if (      is_category() // Change to is_tax() for custom taxonomy pages
             && ( $cat = get_queried_object() ) 
        ) {
            $permalink = esc_url( add_query_arg( [\'ref\' => $cat->term_id], $permalink ) );
        }
        return $permalink;
    });
    
    /*
     * Create our custom adjacent post link 
     */
    function get_referred_adjacent_post( $args = [] ) 
    {
        //First check if we are on a single post, else return false
        if ( !is_single() )
            return false;
    
        //Defaults arguments set for the function. 
        $defaults = [
            \'previous\'       => true,
            \'anchor_text\'    => \'%anchor\',
            \'post_link_text\' => \'%text\',
            \'span_text_prev\' => __( \'Older post: \' ),
            \'span_text_next\' => __( \'Newer post: \' ),
        ];  
    
        $combined_args = wp_parse_args( $args, $defaults );
    
        /**
         * Get the currently displayed single post. For this use 
         * get_queried_object() as this is more safe than the global $post
         *
         * The $post global is very easily changed by any poorly written custom query
         * or function, and is there for not reliable
         *
         * @see Post below on WPSE for explanation
         * @link https://wordpress.stackexchange.com/q/167706/31545
        */ 
        $current_post       = get_queried_object();
        $current_post_date  = $current_post->post_date;
        $current_post_type  = $current_post->post_type;
    
        //Set the important parameters to either get the next post or previous post
        $previous = $combined_args[\'previous\'];
        $order    = ( $previous ) ? \'DESC\' : \'ASC\';
        $op       = ( $previous ) ? \'before\' : \'after\';
    
        // Check if we have a referrer, if so, we need to set this to get the next post in this specific referrer category
        $cat_id = filter_input( INPUT_GET, \'ref\', FILTER_VALIDATE_INT );
    
        if ( $cat_id )
            $custom_args = [\'cat\' => $cat_id];
    
        /**
         * Set the default arguments to merge with the referrer arguments
         *
         * Uses date_query (introduced Wordpress 3.7) to calculate the appropriate adjacent post
         * @see http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters
        */ 
        $query_args = [
            \'post_type\'         => $current_post_type,
            \'posts_per_page\'    => 1,
            \'order\'             => $order,
            \'no_found_rows\'     => true,
            \'suppress_filters\'  => true,
            \'date_query\'        => [
                [
                    $op         => $current_post_date,
                    \'inclusive\' => false
                ]
            ]
        ];
    
        $query_args = ( isset( $custom_args ) ) ? wp_parse_args( $custom_args, $query_args ) : $query_args;
    
        $q = new WP_Query( $query_args );
    
        //If there are no post found, bail early
        if( !$q->have_posts() === 0 )
            return false;
    
        //If there are posts, continue
        $adjacent_post = $q->posts[0];
    
        //Build the permalinks for the adjacent post
        $permalink = get_permalink( $adjacent_post->ID );
    
        // Return the correct permalink, we should add our referrer to the link now if this post was referred
        $link = ( $cat_id ) ? add_query_arg( [\'ref\' => $cat_id], $permalink ) : $permalink;
    
        // Set up out link text to display
        $span_text = ( $combined_args[\'previous\'] ) ? $combined_args[\'span_text_prev\'] : $combined_args[\'span_text_next\'];
        $span = \'<span class="meta-nav">\' . $span_text . \'</span>\';
    
        // Create our anchor and post title text. By default. The post title is used
        $anchor_text = ( $combined_args[\'anchor_text\'] == \'%anchor\' )  ? $adjacent_post->post_title : $combined_args[\'anchor_text\'];
        $post_title  = ( $combined_args[\'post_link_text\'] == \'%text\' ) ? $adjacent_post->post_title : $combined_args[\'post_link_text\'];
    
        //Create the link with title name and anchor text
        $adjacent_post_link = $span . \'<a href="\' . $link . \'" title="\' . $anchor_text . \'">\' . $post_title . \'</a>\';
    
        return $adjacent_post_link;
    }
    
    // Create the next post link - Return the post link
    function get_next_adjacent_post_link( $anchor_text = \'%anchor\', $post_link_text = \'%text\', $span_text_next = \'Newer post: \' )
    {
        $args = [
            \'previous\'       => false,
            \'anchor_text\'    => $anchor_text,
            \'post_link_text\' => $post_link_text,
            \'span_text_next\' => $span_text_next,
        ];
        return get_referred_adjacent_post( $args );
    }
    
    // Create the previous post link - Return the post link
    function get_previos_adjacent_post_link( $anchor_text = \'%anchor\', $post_link_text = \'%text\', $span_text_prev = \'Older post: \' )
    {
        $args = [
            \'previous\'       => true,
            \'anchor_text\'    => $anchor_text,
            \'post_link_text\' => $post_link_text,
            \'span_text_prev\' => $span_text_prev,
        ];
        return get_referred_adjacent_post( $args );
    }
    
    // Create the next post link - Echo post link
    function next_adjacent_post_link( $anchor_text = \'%anchor\', $post_link_text = \'%text\', $span_text_next = \'Newer post: \' )
    {
        echo get_next_adjacent_post_link( $anchor_text, $post_link_text, $span_text_next );
    }
    
    // Create the previous post link - Echo post link
    function previos_adjacent_post_link( $anchor_text = \'%anchor\', $post_link_text = \'%text\', $span_text_prev = \'Older post: \' )
    {
        echo get_previos_adjacent_post_link( $anchor_text, $post_link_text, $span_text_prev );
    }
    
    您现在应该在单曲中添加以下内容。php:

    显示自定义文本

    $referrer = filter_input( INPUT_GET, \'ref\', FILTER_VALIDATE_INT ); // This validate and checks if our referrer "ref" is set
    if ( $referrer ) {
        $category = get_category( $referrer );
        echo \'<h2>\' . $category->name . \'</h2>\';
    }
    
    显示您的帖子链接

    if ( function_exists( \'next_adjacent_post_link\' ) )
        next_adjacent_post_link();
    if ( function_exists( \'previos_adjacent_post_link\' ) )
        previos_adjacent_post_link();
    
    只需在链接中添加相关标记即可。还要检查接受的参数以自定义链接显示的文本。

    这将为你的人生道路奠定基础。您应该能够自定义此项以满足您的确切需要

    SO网友:s_ha_dum

    对于一篇包含多个类别的文章,在H2标签中以一个类别作为标题的最简单方法是什么?

    $c = get_the_category();
    if (!empty($c[0])) {
      echo $c[0]->name;
    }
    
    我不知道会话是如何或为什么会变成这样的。

    SO网友:YuriGoul

    在我找到这个之前,我已经找了两天了,为什么这不是WP中的标准行为,我无法理解。我唯一发现的是那些不再工作的插件和代码,它们没有考虑到存在分层类别,并且可能有多个标签和类别附加到一篇文章上。

    仅供参考:我扩展了van Pieter Goosen的代码,也包括了标签。我还纠正了一些问题,即在该行末尾显示的下一个和前一个链接指向不在那里的帖子。我决定将普通的next prev post和next pref从这段代码中分离出来。php。我没有做的事情是使用menu\\u order作为排序-因为我有一个自定义的post-order-啊,好吧。

    这现在在我的功能中。php:

    /*
     * Add our custom query vars so Wordpress can read it
     */
    add_filter( \'query_vars\', function ( $vars )
    {
        array_push($vars, "ref", "thetype");
        return $vars;
    });
    
    /*
     * Add our referrer to single post links if we are on a category page
     */
    add_filter(\'post_link\', function( $permalink ) // Change to post_type_link for custom post type posts
    {
        if (      is_category() // Change to is_tax() for custom taxonomy pages
             && ( $cat = get_queried_object() )
        ) {
            $permalink = esc_url( add_query_arg( [\'ref\' => $cat->term_id], $permalink ) );
            $permalink = esc_url( add_query_arg( [\'thetype\' => \'category\'], $permalink ) );
        }
    
        if (      is_tag() // Change to is_tax() for custom taxonomy pages
             && ( $cat = get_queried_object() )
        ) {
            $permalink = esc_url( add_query_arg( [\'ref\' => $cat->term_id], $permalink ) );
            $permalink = esc_url( add_query_arg( [\'thetype\' => \'tag\'], $permalink ) );
        }
    
        return $permalink;
    
    });
    
    /*
     * Create our custom adjacent post link
     */
    function get_referred_adjacent_post( $args = [] )
    {
        //First check if we are on a single post, else return false
        if ( !is_single() )
            return false;
    
        //Defaults arguments set for the function.
        $defaults = [
            \'previous\'       => true,
            \'anchor_text\'    => \'%anchor\',
            \'post_link_text\' => \'%text\',
            \'span_text_prev\' => __( \'Older post: \' ),
            \'span_text_next\' => __( \'Newer post: \' ),
        ];
    
        $combined_args = wp_parse_args( $args, $defaults );
    
        /**
         * Get the currently displayed single post. For this use
         * get_queried_object() as this is more safe than the global $post
         *
         * The $post global is very easily changed by any poorly written custom query
         * or function, and is there for not reliable
         *
         * @see Post below on WPSE for explanation
         * @link https://wordpress.stackexchange.com/q/167706/31545
        */
        $current_post       = get_queried_object();
        $current_post_date  = $current_post->post_date;
        $current_post_type  = $current_post->post_type;
        $current_post_ID    = $current_post->ID;
    
    
        //Set the important parameters to either get the next post or previous post
        $previous = $combined_args[\'previous\'];
        $order    = ( $previous ) ? \'DESC\' : \'ASC\';
        $op       = ( $previous ) ? \'before\' : \'after\';
        $css_class = $combined_args[\'css_class\'];
    
        // Check if we have a referrer, if so, we need to set this to get the next post in this specific referrer category
        $mytype = filter_input( INPUT_GET, \'thetype\');
        if ($mytype == \'category\')
            {
                $cat_id = filter_input( INPUT_GET, \'ref\', FILTER_VALIDATE_INT );
                 if ( $cat_id )
                $custom_args = [\'cat\' => $cat_id];
    
            }
        else
            {
            $cat_id = filter_input( INPUT_GET, \'ref\', FILTER_VALIDATE_INT );
                 if ( $cat_id )
                $custom_args = [\'tag_id\' => $cat_id];
    
            }
    
    
        /**
         * Set the default arguments to merge with the referrer arguments
         *
         * Uses date_query (introduced Wordpress 3.7) to calculate the appropriate adjacent post
         * @see http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters
        */
        $query_args = [
            \'post_type\'         => $current_post_type,
            \'posts_per_page\'    => 1,
            \'order\'             => $order,
            \'no_found_rows\'     => true,
            \'suppress_filters\'  => true,
            \'date_query\'        => [
                [
                    $op         => $current_post_date,
                    \'inclusive\' => false
                ]
            ]
        ];
    
        $query_args = ( isset( $custom_args ) ) ? wp_parse_args( $custom_args, $query_args ) : $query_args;
    
        $q = new WP_Query( $query_args );
    
        //If there are no post found, bail early
        if( !$q->have_posts() === 0 )
            return false;
    
        //If there are posts, continue
        $adjacent_post = $q->posts[0];
    
        if( empty($adjacent_post->ID) ) return false;
    
        //Build the permalinks for the adjacent post
        $permalink = get_permalink( $adjacent_post->ID );
    
        // Return the correct permalink, we should add our referrer to the link now if this post was referred
        $link = ( $cat_id ) ? add_query_arg( [\'ref\' => $cat_id, \'thetype\' => $mytype], $permalink ) : $permalink;
    
    
        // Set up out link text to display
    $span_text = ( $combined_args[\'previous\'] ) ? $combined_args[\'span_text_prev\'] : $combined_args[\'span_text_next\'];
    $span = \'<span class="meta-nav">\' . $span_text . \'</span>\';
    
    // Create our anchor and post title text. By default. The post title is used
    $anchor_text = ( $combined_args[\'anchor_text\'] == \'%anchor\' )  ? $adjacent_post->post_title : $combined_args[\'anchor_text\'];
    $post_title  = ( $combined_args[\'post_link_text\'] == \'%text\' ) ? $adjacent_post->post_title : $combined_args[\'post_link_text\'];
    
    //Create the link with title name and anchor text
    $adjacent_post_link = $span . \'<a href="\' . $link . \'" class="\' . $css_class . \'" title="\' . $anchor_text . \'">\' . $post_title . \'</a>\';
        return $adjacent_post_link;
    }
    
    // Create the next post link - Return the post link
    function get_next_adjacent_post_link( $anchor_text = \'%anchor\', $post_link_text = \'%text\', $span_text_next = \'Newer post: \' )
    {
        $args = [
            \'previous\'       => false,
            \'anchor_text\'    => $anchor_text,
            \'post_link_text\' => $post_link_text,
            \'span_text_next\' => $span_text_next,
            \'css_class\'      => "post-nav-next",
        ];
        return get_referred_adjacent_post( $args );
    }
    
    // Create the previous post link - Return the post link
    function get_previos_adjacent_post_link( $anchor_text = \'%anchor\', $post_link_text = \'%text\', $span_text_prev = \'Older post: \' )
    {
        $args = [
            \'previous\'       => true,
            \'anchor_text\'    => $anchor_text,
            \'post_link_text\' => $post_link_text,
            \'span_text_prev\' => $span_text_prev,
            \'css_class\'      => "post-nav-prev",
        ];
        return get_referred_adjacent_post( $args );
    }
    
    // Create the next post link - Echo post link
    function next_adjacent_post_link( $anchor_text = \'%anchor\', $post_link_text = \'%text\', $span_text_next = \'Next post \' )
    {
        echo get_next_adjacent_post_link( $anchor_text, $post_link_text, $span_text_next );
    }
    
    // Create the previous post link - Echo post link
    function previos_adjacent_post_link( $anchor_text = \'%anchor\', $post_link_text = \'%text\', $span_text_prev = \'Previous post \' )
    {
        echo get_previos_adjacent_post_link( $anchor_text, $post_link_text, $span_text_prev );
    }
    
    从单曲开始。php:

    <?php $referrer = filter_input( INPUT_GET, \'ref\', FILTER_VALIDATE_INT );?>
    <!-- // checks if our referrer "ref" is set -->
    <?php if ( $referrer ): ?>
    
            if ( function_exists( \'next_adjacent_post_link\' ) )
            next_adjacent_post_link();
            if ( function_exists( \'previos_adjacent_post_link\' ) )
            previos_adjacent_post_link();
    
    <?php else: ?> <!--else referer -->
    
        <!--normal prev next links here -->
    
    <?php endif; ?> <!-- end if refferer -->
    

    结束

    相关推荐

    向GET_CATEGORIES下拉列表添加自定义选项

    我有一个下拉菜单,用于在我正在处理的小部件中选择类别。一切正常,选项保存在数据库中。我现在要做的是添加一个空白选项,而不是在单击“保存”时自动设置。在这种情况下,用户可能不想设置类别。 $this->categories = get_categories(); foreach ( $this->categories as $cat ) { $selected = ( $cat->term_id == esc_att