简体   繁体   English

PHP / WordPress:在foreach循环中覆盖page_id

[英]PHP/WordPress: override page_id in foreach loop

I have a WordPress site and currently the code it set to create titles based on the page title. 我有一个WordPress网站,当前将其代码设置为根据页面标题创建标题。 The titles are: Interior House Painting, Exterior House Painting and Commercial Painting. 标题是:内部房屋绘画,外部房屋绘画和商业绘画。 I would like to override the titles to remove the word "house". 我想覆盖标题以删除“ house”一词。 This is the code currently: 这是当前的代码:

<?php
// interior_painting: 18
// exterior_painting: 25
// other services: 36
$page_ids = array(18, 25, 36);
$images = array('servicesInterior.jpg', 'servicesExterior.jpg', 'servicesOther.jpg');
foreach ($page_ids as $key => $page_id) {
    $page_post = get_post($page_id);
    $page_custom_key = 'home_page_info';
    $page_link = $page_post->post_name;
    $li_class = $page_id == 36 ? 'noMargin' : '';
    $title = $page_id == 18 ? 'Interior Painting' : $page_post->post_title . " ";
    $title = $page_id == 36 ? 'Commercial Projects' : $page_post->post_title . " ";
    $title = $page_id == 25 ? 'Exterior Painting' : $page_post->post_title . " ";


    echo '<li class="' . $li_class . '"> <a href="' . $page_link . '">';
    echo '<img class="alignright size-full wp-image-349" title="servicesInterior" src="/wp-content/uploads/2011/04/' . $images[$key] . '" alt="" width="200" height="95" /></a>';
    echo '<h2>' . $title . '</h2>';
    echo get_post_meta($page_id, $page_custom_key, true);
    echo '<a class="btn-find-more" href="' . $page_post->post_name . '">FIND OUT MORE</a></li>';
}

?>

The output is this: Interior House Painting, Exterior Painting, Commercial Painting. 输出为:室内房屋绘画,外部绘画,商业绘画。 How do I get "house" removed from "Interior House Painting"? 如何从“室内房屋绘画”中删除“房屋”?

只需使用preg_replace('House'|| 'house','',/*Variable Page title is in*/);

You could try replacing the line: 您可以尝试替换该行:

echo '<h2>' . $title . '</h2>';

With something like this: 用这样的东西:

if (is_page('Interior House Painting')) { echo '<h2>Interior Painting</h2>'; } 
if (is_page('Exterior House Painting')) { echo '<h2>Exterior Painting</h2>'; } 
else { echo '<h2>' . $title. '</h2>'; }
$title = ucwords(trim(strtolower(str_replace('house', '', $page_post->post_title))));

Though, I am a little curious as to why you would not prefer to just remove the word from the title altogether. 但是,对于您为什么不希望只从标题中完全删除单词,我有点好奇。

ADDITIONALLY: Somebody else mentioned using preg_replace. 另外:有人提到使用preg_replace。 That's also entirely possible, but it would be best to do a case-insensitive search: 这也是完全可能的,但是最好进行不区分大小写的搜索:

$title = trim(preg_replace('/house/i', '', $page_post->post_title));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM