【问题标题】:How can i limit wordpress title length in my wordpress theme?如何在我的 wordpress 主题中限制 wordpress 标题长度?
【发布时间】:2019-04-11 16:04:12
【问题描述】:

所以我购买了这个 wordpress 主题,我想对其进行调整,使其看起来像 blog.asana.com。首先是为了学习目的,因为我喜欢它的外观,所以我正在尝试使用这些功能。

我在这里遇到不同的问题,但首先我使用的是儿童主题。我正在尝试在主页上更改我的博客文章的标题,以便它们最多显示 2 行。它看起来更好,因为我的主题使用某种砖石展示,我更喜欢这种方式。 因为如果我的问题听起来很愚蠢,我不太习惯这种抱歉。 此外,由于这不是我的主题,我不确定如何解决问题。如果没有它永远加载并显示和错误,我似乎无法向functions.php添加东西

我尝试在子主题function.php 中使用它,但没有成功。 我也在父主题function.php中尝试过

function max_title_length( $title ) {
$max = 20;
if( strlen( $title ) > $max ) {
return substr( $title, 0, $max ). " …";
} else {
return $title;
}
}

我说的博客是 blog.asana.com,我的主题是 blog(dot)nocturn(dot)ch

【问题讨论】:

    标签: wordpress themes trim


    【解决方案1】:

    您好,您想只在主页上显示两行。

    这样使用:

    add_filter( 'the_title', 'max_title_length' );
    function max_title_length( $title ) {
        $max = 20;
        if( is_home() && strlen( $title ) > $max ) {
            $title = substr( $title, 0, $max ) . " …";
        }
        return $title;
    }
    

    这仅适用于帖子页面。

    【讨论】:

    • 非常感谢!我应该把它放在子主题functions.php中吗?
    • 这仍然会限制仅博客文章范围之外的事物的标题,例如,如果他要显示主页的标题并且任何导航元素仍将被过滤
    【解决方案2】:

    你需要过滤 the_title();如果这不起作用,则对 wp_title() 执行相同操作;这取决于主题用于引入页面标题的内容。

    经过测试和测试可以正常工作:

    add_filter( 'the_title', 'max_title_length' );
    function max_title_length( $title ) {
        $max = 20;
        if( strlen( $title ) > $max ) {
            $title = substr( $title, 0, $max ) . " …";
            return $title;
        } else {
            return $title;
        }
    }
    

    这将使用 the_title() 编辑所有标题;

    然后,您可以使用各种 WordPress 函数过滤要定位的页面和要定位的用例,只需将它们与带有“&&”的 JavaScript if 语句结合起来:

    • is_home()
    • is_frontpage()
    • is_single()

    更多可以found here

    例子:

    If( strlen($title) > $max && is_home() ) {
    

    【讨论】:

    • 谢谢。但是,如果我只想修改主页个别博客文章摘录上的标题长度,这不会做吗?
    • 请添加用于为我显示个人博客的代码
    • 这对我来说有点困难,因为我目前正在使用主题。你想看看我的网站管理面板吗?我可以给你权限:)
    • 请给我发消息
    • stackoverflow 上没有消息系统吗?我在哪里可以联系到你? :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    相关资源
    最近更新 更多