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

WooCommerce我的账户:从作者获取自定义文章类型的文章ID

解决WooCommerce账户页链接指向用户专属stallholders自定义文章编辑页的问题

问题背景

网站通过表单为登录用户生成专属的stallholders自定义文章类型页面,已在WooCommerce「我的账户」菜单添加「Edit Stall Information」链接,但修改代码后,链接跳转到用户ID对应的用户编辑页,而非用户专属的stallholders文章编辑页。

错误原因

原修改代码中使用$current_user->post_ID是错误的:WordPress的用户对象(WP_User)不存在post_ID属性,此代码实际获取的是用户自身的ID(wp_users表的ID),而非关联的stallholders文章ID。

解决方案

需要通过WP_Query查询当前用户关联的stallholders文章,再生成对应的编辑页URL。以下分两种常见关联场景给出代码:

场景1:stallholders文章的作者设置为当前用户

如果生成stallholders文章时,将文章的post_author字段设为当前用户ID,使用以下代码替换原hook_endpoint函数:

// 重写stall-page端点的URL
add_filter( 'woocommerce_get_endpoint_url', 'hook_endpoint', 10, 4 );
function hook_endpoint( $url, $endpoint, $value, $permalink ){
    // 非目标端点直接返回原URL
    if( 'stall-page' !== $endpoint ) {
        return $url;
    }

    $current_user = wp_get_current_user();
    // 未登录用户返回原URL
    if ( !$current_user->ID ) {
        return $url;
    }

    // 查询当前用户作为作者的stallholders文章
    $stall_query = new WP_Query( array(
        'post_type'      => 'stallholders',
        'post_status'    => array( 'publish', 'draft' ), // 包含已发布和草稿状态
        'author'         => $current_user->ID,
        'posts_per_page' => 1, // 每个用户仅对应一篇,取第一条结果
        'no_found_rows'  => true, // 关闭结果计数优化查询性能
    ) );

    if ( $stall_query->have_posts() ) {
        $stall_post = $stall_query->posts[0];
        // 使用admin_url生成后台编辑页URL,适配多环境
        $url = admin_url( 'post.php?post=' . $stall_post->ID . '&action=edit' );
    } else {
        // 未找到对应文章时,跳转到stallholders列表页
        $url = admin_url( 'edit.php?post_type=stallholders' );
    }

    wp_reset_postdata(); // 重置查询状态,避免影响后续内容
    return $url;
}

场景2:stallholders文章通过自定义字段关联用户ID

如果生成stallholders文章时,使用自定义字段(例如associated_user_id)存储对应用户ID,只需将上述代码中的WP_Query参数替换为:

$stall_query = new WP_Query( array(
    'post_type'      => 'stallholders',
    'post_status'    => array( 'publish', 'draft' ),
    'meta_key'       => 'associated_user_id', // 替换为实际使用的自定义字段键名
    'meta_value'     => $current_user->ID,
    'meta_compare'   => '=',
    'posts_per_page' => 1,
    'no_found_rows'  => true,
) );

关键优化点

  • 使用admin_url()代替硬编码域名,适配本地开发、生产等不同环境
  • 增加端点判断和未登录校验,避免无效查询
  • 限制查询结果数量并关闭计数,优化性能
  • 未找到对应文章时降级到列表页,提升用户体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 11:12:08