繁体   English   中英

Wordpress - 强制使用随机值的帖子永久链接、帖子别名或帖子名称

[英]Wordpress - Force the post permalink, post slug or post name with random values

我有一个wordpress的设置,里面宣传了一系列特殊产品,不知道名字,也不能进入页面。

通过 301 重定向,我解决了无法进入产品页面的问题。

为了安全起见,我希望产品的永久链接是一个随机字符串,这样无论您尝试多少,都无法进入产品页面。

这是我的 PHP 代码:

function generateRandomUrl(){
    $char = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'o', 'O', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T', 'u', 'U', 'v', 'V', 'y', 'Y', 'x', 'X', 'z', 'Z');
    $cont = 0;
    $str = "";
    while ($cont < 20){
        $random = random_int(0, count($char)-1);
        $str .= $char[$random];
        $cont ++;
    }
    return $str;
}

$url = generateRandomUrl();
$post_data = array(
    'post_author' => $usuarioPropietario,
    'post_name' => $url, /* SLUG */
    'post_title' => $_POST['name'],
    'post_content' => $_POST['comment'],
    'post_excerpt' => $_POST['contenido'],
    'post_status' => 'pending', /* PENDIENTE */
    'ping_status' => 'closed',
    'post_type' => 'product',
);

$product_id = wp_insert_post( $post_data );

我的问题是,当产品是由管理员或编辑用户创建时,它可以正常工作。 但是当一个用户已经在页面上注册,并且不是管理员或编辑时,所有的内容都是正确的,但是'post_name'不起作用。

如果我没记错的话,是将 slug 或永久链接分配给 Woocommerce 产品的“post_name”字段的值。

有什么办法可以强制 post_name 字段的值吗? 在普通用户的情况下,它似乎采用“post_title”字段的值。

您可以将随机 function 挂钩到操作save_post

您可以在functions.php中使用我的以下代码

add_action( 'save_post', 'random_product_slug', 10, 3 );
function random_product_slug( $post_id, $post, $update ) {

    // Only run on product
    if ($post->post_type != 'product' || $post->post_status == 'auto-draft') {
        return;
    }

    // temporary remove this action because if will make loop when we call wp_update_post
    remove_action( 'save_post', 'random_product_slug', 10, 3 );

    // update product
    wp_update_post( array(
        'ID' => $post_id,
        'post_name' => generateRandomUrl()  // random slug/post_name
    ));

    // add this action to save_post again to make next product will have this action
    add_action( 'save_post', 'random_product_slug', 10, 3 );
}

function generateRandomUrl() {
    $char = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'o', 'O', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T', 'u', 'U', 'v', 'V', 'y', 'Y', 'x', 'X', 'z', 'Z');
    $cont = 0;
    $str = "";
    while ($cont < 20){
        $random = random_int(0, count($char)-1);
        $str .= $char[$random];
        $cont ++;
    }
    return $str;
}

有什么办法可以强制 post_name 字段的值吗? 在普通用户的情况下,它似乎采用“post_title”字段的值。

Product slug 仅使用 post_name。 所有像创建/更新产品这样的操作都将通过save_post操作运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM