You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法在WordPress类中调用get_post函数,返回null求解决方案

问题分析与解决办法

核心问题

你的代码存在两个关键问题:

  1. 调用时机过早:实例化类后立刻执行get_email_recipients(),此时init钩子还未触发,$this->post完全没被赋值。
  2. 依赖不可靠的全局上下文:init钩子触发时,很多场景下(比如首页、后台非文章编辑页)并没有有效的全局$post对象,get_post()自然返回null。

具体修复方案

方案1:调整钩子与调用时机,确保Post对象已加载

将初始化逻辑绑定到更晚的钩子(比如template_redirect前端页面、load-post.php后台文章编辑页),同时不要直接在实例化后调用依赖Post的方法,而是通过钩子触发:

namespace Maid_Brigade;
class Franchise {

    protected $post;

    public function __construct() {
        // 前端页面用template_redirect,此时Post对象已加载
        add_action( 'template_redirect', [ $this, 'init' ] );
        // 后台文章编辑页用load-post.php钩子
        add_action( 'load-post.php', [ $this, 'init' ] );
        // 绑定收件人处理逻辑到钩子
        add_action( 'template_redirect', [ $this, 'process_email_recipients' ] );
    }

    public function get_email_recipients() {
        return $this->get_block_attribute('recipients');
    }

    public function get_block_attribute( $attribute ) {
        // 先判断Post是否存在,避免报错
        if ( ! $this->post || ! isset( $this->post->post_content ) ) {
            return null;
        }
        
        $blocks = parse_blocks( $this->post->post_content );
        $attribute_value = null;
        
        // 遍历区块查找目标属性
        foreach ( $blocks as $block ) {
            // 替换成你实际的区块名称
            if ( $block['blockName'] === 'maid-brigade/email-recipient-block' ) {
                $attribute_value = $block['attrs'][ $attribute ] ?? null;
                break;
            }
        }
        return $attribute_value;
    }

    public function init() {
        // 用get_queried_object()获取当前查询的Post对象,比get_post()更可靠
        $this->post = get_queried_object();
        // 如果需要指定特定Post,直接传ID:$this->post = get_post( 123 );
    }

    // 实际处理收件人的逻辑,通过钩子触发
    public function process_email_recipients() {
        $recipients = $this->get_email_recipients();
        if ( $recipients ) {
            // 这里写你的邮件发送或其他业务逻辑
        }
    }
}

// 在functions.php中实例化
$maid_brigade_franchise = new Maid_Brigade\Franchise();

方案2:明确传入Post ID(适用于需要特定Post的场景)

如果你的逻辑不需要依赖当前页面的Post,而是固定某篇文章,可以直接在调用时传入ID,彻底摆脱上下文依赖:

// 修改get_block_attribute方法,支持传入Post ID
public function get_block_attribute( $attribute, $post_id = null ) {
    $post = $post_id ? get_post( $post_id ) : $this->post;
    if ( ! $post ) {
        return null;
    }
    
    $blocks = parse_blocks( $post->post_content );
    // 后续遍历逻辑不变
}

// 调用时直接传ID
$recipients = $maid_brigade_franchise->get_block_attribute('recipients', 456);

关键注意点

  • 永远不要在init及更早的钩子中依赖全局$post对象,此时Post数据还未完成加载。
  • 增加null判断,避免因Post对象不存在导致PHP报错。
  • 如果是后台场景,根据具体页面选择对应的钩子(比如load-post-new.php对应新建文章页)。

内容的提问来源于stack exchange,提问作者Grzes Slania

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 03:05:24