


How to make the WordPress editor support inline SVG code, wordpresssvg_PHP tutorial
How to make the WordPress editor support inline SVG code, wordpresssvg
The WordPress editor’s support for SVG has always been very unfriendly. First of all, it cannot upload SVG files; Automatically embed into the content so that it displays normally. At the same time, the inline SVG code is not recognized at all, and the SVG code will be automatically deleted ruthlessly.
In the previous article, I introduced how to make WordPress support uploading SVG images, which seems to partially solve this problem. Recently, during the development process, I have encountered a large number of situations where I need to use inline SVG (inline SVG) code in the WordPress visual editor.
I believe you also know that WordPress uses the TinyMCE editor, and the TinyMCE editor only supports standard HTML5 tags and does not recognize SVG codes. When I select "Visualization" and "Text" in the WordPress editor When switching between the two tabs, all SVG code is cleanly deleted.
There are many discussions on the Internet about how to make WordPress’s TinyMCE support SVG. The documentation for configuring TinyMCE extension tags was also found on the TinyMCE official website. There are mainly three configuration points: extended_valid_elements, custom_elements and valid_children. The following is a code copied from the Internet and provided by netizens to configure the WordPress editor:
add_filter('tiny_mce_before_init', 'vsl2014_filter_tiny_mce_before_init'<span>); </span><span>function</span> vsl2014_filter_tiny_mce_before_init( <span>$options</span><span> ) { </span><span>if</span> ( ! <span>isset</span>( <span>$options</span>['extended_valid_elements'<span>] ) ) { </span><span>$options</span>['extended_valid_elements'] = 'svg'<span>; } </span><span>else</span><span> { </span><span>$options</span>['extended_valid_elements'] .= ',svg'<span>; } </span><span>if</span> ( ! <span>isset</span>( <span>$options</span>['valid_children'<span>] ) ) { </span><span>$options</span>['valid_children'] = '+body[svg]'<span>; } </span><span>else</span><span> { </span><span>$options</span>['valid_children'] .= ',+body[svg]'<span>; } </span><span>if</span> ( ! <span>isset</span>( <span>$options</span>['custom_elements'<span>] ) ) { </span><span>$options</span>['custom_elements'] = 'svg'<span>; } </span><span>else</span><span> { </span><span>$options</span>['custom_elements'] .= ',svg'<span>; } </span><span>return</span> <span>$options</span><span>; }</span>
Some netizens think that the following is enough:
<span>function</span> override_mce_options(<span>$initArray</span><span>) { </span><span>$opts</span> = '*[*]'<span>; </span><span>$initArray</span>['valid_elements'] = <span>$opts</span><span>; </span><span>$initArray</span>['extended_valid_elements'] = <span>$opts</span><span>; </span><span>return</span> <span>$initArray</span><span>; } add_filter(</span>'tiny_mce_before_init', 'override_mce_options');
Some netizens gave the following suggestions:
None of the suggestions above seem to be successful individually, but each seems to solve part of the problem. After repeated experiments, I finally found the following method, which can successfully prevent SVG from being deleted in the TinyMCE editor of WordPress, and save it in a good format.
First add the following PHP code in function.php
:
<span>/*</span><span>* * Add to extended_valid_elements for TinyMCE * * @param $init assoc. array of TinyMCE options * @return $init the changed assoc. array </span><span>*/</span> <span>function</span> my_change_mce_options( <span>$init</span><span> ) { </span><span>$ext</span> = 'a[*],altglyph[*],altglyphdef[*],altglyphitem[*],animate[*],animatecolor[*],animatemotion[*],animatetransform[*],circle[*],clippath[*],color-profile[*],cursor[*],defs[*],desc[*],ellipse[*],feblend[*],fecolormatrix[*],fecomponenttransfer[*],fecomposite[*],feconvolvematrix[*],fediffuselighting[*],fedisplacementmap[*],fedistantlight[*],feflood[*],fefunca[*],fefuncb[*],fefuncg[*],fefuncr[*],fegaussianblur[*],feimage[*],femerge[*],femergenode[*],femorphology[*],feoffset[*],fepointlight[*],fespecularlighting[*],fespotlight[*],fetile[*],feturbulence[*],filter[*],font[*],font-face[*],font-face-format[*],font-face-name[*],font-face-src[*],font-face-uri[*],foreignobject[*],g[*],glyph[*],glyphref[*],hkern[*],line[*],marker[*],mask[*],metadata[*],missing-glyph[*],mpath[*],path[*],pattern[*],polygon[*],polyline[*],radialgradient[*],rect[*],script[*],set[*],stop[*],lineargradient[*],style[*],svg[*],switch[*],symbol[*],text[*],textpath[*],title[*],tref[*],tspan[*],use[*],view[*],vkern[*]'<span>; </span><span>//</span><span> Add to extended_valid_elements if it alreay exists</span> <span>if</span> ( <span>isset</span>( <span>$init</span>['extended_valid_elements'<span>] ) ) { </span><span>$init</span>['extended_valid_elements'] .= ',' . <span>$ext</span><span>; } </span><span>else</span><span> { </span><span>$init</span>['extended_valid_elements'] = <span>$ext</span><span>; } </span><span>//</span><span> Super important: return $init!</span> <span>return</span> <span>$init</span><span>; } add_filter(</span>'tiny_mce_before_init', 'my_change_mce_options');
In the above WordPress filter, I added all SVG tag elements (as for the method of using wildcards '*[*]', I have not tried it. Interested friends can try it, and you are welcome to give it a try) Give feedback. )
Careful friends may have noticed that the SVG tag names above have all been changed to lowercase. Obviously, the official SVG specification stipulates that the case of SVG tag names is meaningful. But I have experimented and using camel case SVG tag names does not work. Maybe the HTML code doesn't care about case.
Second, in the TinyMCE editor of WordPress, wrap all SVG codes with
, so that the TinyMCE editor can maintain the original indentation format of the SVG code.Third, put something in the code, such as , or a sentence "Sorry, your browser does not support SVG":
<span><</span><span>svg</span><span>></span> <span><</span><span>rect</span><span>></span> ... <span></</span><span>rect</span><span>></span><span> 抱歉,你的浏览器不支持SVG </span><span></</span><span>svg</span><span>></span>
After implementing the above method, I now use Wordpress’s TinyMCE editor. After embedding the SVG code, it is just like writing ordinary html code and will not be deleted or deleted. I have not conducted an in-depth study of the TinyMCE editor's processing mechanism of SVG code. The above methods only treat the symptoms but not the root cause. Maybe with the upgrade of WordPress or the upgrade of TinyMCE, these methods will become invalid.
If you have a more clever method, please share it in the comments, thank you!
Original address: http://www.manongjc.com/article/657.html
Related reading:
Let WordPress support uploading SVG images
Detailed explanation of how to use the wp_title() function in WordPress
Introduction to the usage of several animation elements in SVG

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)
