WordPress 将 php 代码运行到 the_content 循环中

没有人x3

我正在学习 PHP 和 WordPress 开发,所以我认为也许在这里我会找到答案或提示。

我已经the_content根据用户角色进行了限制结束后,the_content我想显示特定帖子所独有的按钮。所以这是显示的代码:

function displaycontent($content) {
    if(is_singular( 'custom_post_type' )) {

        $aftercontent = 'I Want To Add Code Here';
        $fullcontent =  $content . $aftercontent;

    } else {
        $fullcontent = $content;
    }

    return $fullcontent;
}
add_filter('the_content', 'displaycontent');

我想将下面的代码插入上面带下划线的地方:

<?php 
$post = $wp_query->post;   
$group_id = get_field( 'link_number' , $post->ID );   
if( $group_id ) {
   echo do_shortcode( '[checkout_button class="button" level="' . $group_id . '" text="Order"]' ); 
}
?>                      

我怎样才能做到这一点?

马格努斯·埃里克森

为此创建自定义短代码可能会更好。如果你改变the_content工作方式,它将是全球性的,无处不在。

注意:
此代码完全未经测试,并在谷歌搜索 5 分钟后拼凑而成,因此,如果出现错误,请随时发表评论,我将对其进行修改。它应该相当接近并且主要用于解释概念而不是纯粹的复制/粘贴解决方案

注册一个新的短代码:

add_shortcode('my_awesome_content', 'my_awesome_content_func');

创建回调函数:

在这里,我们添加$atts了将包含我们的属性(帖子 ID)的内容:

function my_awesome_content_func($atts = [])
{
    $postId = $atts['postid'] ?? null;

    if ($postId === null) {
        // We got no id so let's bail
        return null;
    }

    $post = get_post($postId);

    if (!$post) {
        // We didn't find any post with the id so again, let's bail
        return null;
    }

    $group_id = get_field( 'link_number' , $post->ID );   

    $content = $post->content;

    if( $group_id ) {
        $content .= do_shortcode( '[checkout_button class="button" level="' . $group_id . '" text="Order"]' ); 
    }

    return $content;
}

用法:

现在你应该可以这样调用它:

echo do_shortcode('[my_awesome_content postid="' . $post->ID . '"]');

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章