【问题标题】:Change output of wordpress function inside plugin and use it in wordpress theme更改插件内 wordpress 函数的输出并在 wordpress 主题中使用它
【发布时间】:2019-06-08 17:59:34
【问题描述】:

所以...我正在开发一个 wordpress 插件,它应该改变你从 wordpress 函数 get_the_post_thumbnail_url() 获得的图像来源@

你有一个主题,在那里你得到带有get_the_post_thumbnail_url($id) 的图像源,它返回类似https://wordpress/path/to/image.jpg 的东西,我想在那个插件内部更改该函数的输出,就像我在我的插件中修改它时一样您在主题中使用该功能,它会输出我修改后的版本。

我尝试使用add_filter(),但它不起作用,我什至不知道它是否应该起作用。

function my_function_idk( $example ) {
    $asd = $example.'lul123';
    return $asd;
}
add_filter( 'get_the_post_thumbnail_url', 'my_function_idk' );
// expected output: https://wordpress/path/to/image.jpglul123

实际输出:https://wordpress/path/to/image.jpg

也许我知道你必须使用apply_filters() 才能使过滤器工作,但你需要在那个主题中使用它,我不希望那样。我只是想修改那个功能……可以吗?

我只是不明白他们的文档...我对 wordpress 大发雷霆...fkn bulsht。

【问题讨论】:

    标签: php wordpress plugins wordpress-theming


    【解决方案1】:

    使用像add_filter( 'get_the_post_thumbnail_url_hook', 'my_function_idk' );这样的钩子。在您要挂钩的函数内部需要:

    function get_the_post_thumbnail_url( $post = null, $size = 'post-thumbnail' ) {
        $post_thumbnail_id = get_post_thumbnail_id( $post );
        if ( ! $post_thumbnail_id ) {
            return false;
        }
        return  apply_filters('get_the_post_thumbnail_url_hook', $post_thumbnail_id, $size );
    }
    

    return apply_filters('get_the_post_thumbnail_url_hook', $post_thumbnail_id, $size );

    而且这个函数没有钩子。 Look it inside core。所以你不能“上钩”它。

    但是你有一个选择:
    get_the_post_thumbnail_url 中,我们得到wp_get_attachment_image_urlwp_get_attachment_image_src 并且它的功能有return apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon );

    所以你可以通过函数队列连接到链尾的那个。

    试试看: add_filter( 'wp_get_attachment_image_src', 'my_function_idk', 90, 4 );Documentation

    【讨论】:

    • 嗯...好的,我会试试看,但是 90 和 4 是什么意思?
    • @SenTisso 90 - 如果其他人将连接到同一个钩子,则比其他任何人都更晚地运行您的函数。 4 这是在创建钩子时传递给钩子的参数数量,在这种情况下 - $image, $attachment_id, $size, $icon。
    • 所以效果很好!谢谢!但我还有一个问题,是否可以在 add_filter() 中获取该图像附件的 ID,因为我只得到那个 src(这是有道理的),但我也需要 ID
    • @SenTisso 这个创建的过滤器传递了我上面写的 4 个参数。在您的函数中使用这些参数,例如: `function my_function_idk( $image, $attachment_id, $size, $icon ){/*your code*/} ` "$attachment_id" 是您所需要的。检查一下。
    猜你喜欢
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多