我可以将可重复使用的代码存储在unction.php中,并根据需要应用到其他模板。干代码

时间:2016-01-05 作者:user1355485

我试图将可重用代码应用于某个posttype模板,我想知道是否可以将代码以某种方式存储在函数中。php并将其包含在我想要的地方。

这是代码

 if (!empty( get_field(\'social_title\') )):
    $socialTitle = get_field(\'social_title\');
    $socialContent = get_field(\'social_content\');
    $link = get_field(\'social_link\');
    $cleanString = strip_tags($socialContent);
    $cleanTitle = strip_tags($socialTitle);
else:
    $cleanTitle = strip_tags($postobj->post_title );
    $cleanSocialContent = strip_tags(get_field(\'content\'));
    $shortString = substr ($cleanSocialContent, 0, 137);
    $stringsize = strlen($shortString);
    if ($stringsize > 136):
        $cleanString = $shortString . "...";
    else:
        $cleanString = $shortString;
    endif;
endif;
下面是如何在模板中使用它

<?php if (have_posts()) : while (have_posts()) : the_post();
    /** Post object */
    $postobj = get_post();
    /** Whats the previous post */
    $previous_post = get_previous_post();
    /** whats the next post  */
    $next_post = get_next_post();
    /** Whats the categories  */
    $cats = get_the_category();
    /** grab first categorie  */
    $cat_name = $cats[0]->name;

    /** Post Content in its raw form, so html tags are showing. The $cleanstring has been stripped of the html tags  */
    /** check if Social Content available if not grab the first 100 

    charactors and add a ... to the end  */
        if (!empty( get_field(\'social_title\') )):
    $socialTitle = get_field(\'social_title\');
    $socialContent = get_field(\'social_content\');
    $link = get_field(\'social_link\');
    $cleanString = strip_tags($socialContent);
    $cleanTitle = strip_tags($socialTitle);
else:
    $cleanTitle = strip_tags($postobj->post_title );
    $cleanSocialContent = strip_tags(get_field(\'content\'));
    $shortString = substr ($cleanSocialContent, 0, 137);
    $stringsize = strlen($shortString);
    if ($stringsize > 136):
        $cleanString = $shortString . "...";
    else:
        $cleanString = $shortString;
    endif;
endif;
     ?>
        <?php get_template_part(\'slider-yellow\'); ?>
        <div id="single-article">
            <article class="row">
                <div id="social-icon-cont" class="medium-2 columns">
                    <ul>
                        <li>
                            <a href="#">
                                <span class="social-link facebook-icon"></span>
                            </a>
                        </li>
                        <li>
                            <a class="popup" href="https://twitter.com/intent/tweet?related=SEIU&text=<?php echo $cleanString ?>" target="_blank">
                                <span class="social-link twitter-icon"></span>
                            </a>
                        </li>
                        <li>
                            <a href="mailto:?&subject=<?php echo $cleanTitle ?>&body=<?php echo $cleanString ?>">
                                <span class="social-link share-icon"></span>
                            </a>
                        </li>
                    </ul>
任何帮助都将不胜感激。

提前感谢。

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

在开始之前,如果需要在模板部件之间传递变量,则必须签出this post. 关于如何实现这一点,有一些特殊的答案(特别是来自@kaiser和@gmazzap),特别是不必使用全局变量;-)

您首先需要做的事情有很多,因为我们确实需要避免由于ACF被停用或由于不存在的东西而导致的错误和致命错误。

以下代码未经测试,可能包含错误。请确保首先在本地进行测试。还要注意,代码至少需要PHP 5.4

我从未与ACF合作过,我已经快速阅读了相关文档,并在代码中实现了对文档的理解

根据需要使用、滥用和修改代码。代码是非常静态的,但您可以使其成为动态的。因为我不知道您到底想如何使用它,所以可以扩展它,将链接和feed合并到函数本身中,但这需要您自己来做。

为了便于理解,我对代码进行了注释

代码

/** Function to return either the title or content from an ACF field choice
 *
 * @param (string) $to_return Value are \'title\' or \'content\'
 * @return (string) $output
 */
function get_single_variable( $to_return = \'\' ) 
{
    /**
     * First get our current post object. This section is something I\'m experimenting 
     * with get a reliable way to pass the current post object as $post is not reliable.
     * NOTE: query_posts will break get_queried_object(), this is one reason you should
     * never ever use query_posts
     */
    if ( is_singular() ) {
        $current_post = get_queried_object();
    } else {
        $current_post = get_post();
    }

    // Make sure we have a valid vale for $to_return, if not return an empty string
    if (    \'title\'   !== $to_return
         && \'content\' !== $to_return
    )
        return \'\';


    // Make sure ACF is activated and that get_fields are available. If not, bail out and return an empty strin
    if ( !function_exists( \'get_fields\' ) )
        return \'\';

    // Now that we now get_fields exists and we will not recieve fatal errors, lets safely continue

    // We will now get all the fields belonging to the post at once
    $fields = get_fields( $current_post->ID );
    // ?><pre><?php var_dump( $fields ); ?></pre><?php // For debugging purposes, just uncomment it to dump the value of $fields

    //Set our variables to avoid bugs like undefined variables
    $cleaned_title   = \'\';
    $cleaned_content = \'\';

    // Setup our conditional statements
    $social_title = $fields[\'social_title\'];
    if ( !empty( $social_title ) ) {
        // Use wp_strip_all_tags to use native functions (which is filterable), stip_tags are still valid though
        $cleaned_title   = wp_strip_all_tags( $fields[\'social_title\']   );
        $cleaned_content = wp_strip_all_tags( $fields[\'social_content\'] );
    } else { 
        $cleaned_title = wp_strip_all_tags( $current_post->post_title );

        // Get our content from another field now
        $cleaned_social_content = wp_strip_all_tags( $fields[\'content\'] );
        // Use mb_substr() and mb_strlen() which is multibyte safe
        if ( 136 < mb_strlen( $cleaned_social_content ) ) {
            $excerpt_more    = __( \'&hellip;\' );
            $cleaned_content =  mb_substr( $cleaned_social_content, 0, 137 ) . $excerpt_more;
        } else {
            $cleaned_content = $cleaned_social_content;
        }
    }

    if ( \'title\' === $to_return ) {
        return $cleaned_title;
    } else { 
        return $cleaned_content;
    }
}
现在,您可以在任何地方使用它来显示标题或内容,如下所示

echo get_single_variable( \'title\' );

echo get_single_variable( \'content\' );