在开始之前,如果需要在模板部件之间传递变量,则必须签出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 = __( \'…\' );
$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\' );