qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
294,153
<p>Is there any hook to change the single product thumbnail? I did search a lot on SO as well as over the internet but no luck.</p> <p>With 'thumbnail' I don't mean changing the size of the current image but I want to completely change/replace the product image (thumbnail) with a new image based on some scenario.</p> <pre><code>public function pn_change_product_image_link( $html, $post_id ){ $url = get_post_meta( $post_id ); $alt = get_post_field( 'post_title', $post_id ) . ' ' . __( 'thumbnail', 'txtdomain' ); $attr = array( 'alt' =&gt; $alt ); $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, NULL ); $attr = array_map( 'esc_attr', $attr ); $html = sprintf( '&lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/WP_Suspension_logo.svg/2000px-WP_Suspension_logo.svg.png"', esc_url($url) ); foreach ( $attr as $name =&gt; $value ) { $html .= " $name=" . '"' . $value . '"'; } $html .= ' /&gt;'; return $html; } </code></pre> <p>This is what I'm doing now but it's throwing an error.</p> <p>Filter, Hook:</p> <pre><code>post_thumbnail_html </code></pre>
[ { "answer_id": 294160, "author": "Mahesh", "author_id": 116626, "author_profile": "https://wordpress.stackexchange.com/users/116626", "pm_score": -1, "selected": false, "text": "<p>I hope this filter will help you.</p>\n\n<pre><code>apply_filters( 'woocommerce_single_product_image_thumbnail_html', $sprintf, $post_id ); \n</code></pre>\n\n<p>Ref: <a href=\"http://hookr.io/filters/woocommerce_single_product_image_thumbnail_html/\" rel=\"nofollow noreferrer\">http://hookr.io/filters/woocommerce_single_product_image_thumbnail_html/</a></p>\n" }, { "answer_id": 379901, "author": "Jordan Carter", "author_id": 94213, "author_profile": "https://wordpress.stackexchange.com/users/94213", "pm_score": 0, "selected": false, "text": "<p>Here's what I believe is an updated version of one of the other answers' comments. This function replaces the width and height attributes, but OP wanted to change the src. I imagine the solution would be similar, except using preg_replace to replace the src instead.</p>\n<pre><code>add_action('woocommerce_single_product_image_thumbnail_html','remove_single_product_image_attrs',10,2); \n\nfunction remove_single_product_image_attrs( $sprintf, $post_id ){ \n return preg_replace( '/(width|height)=&quot;\\d*&quot;\\s/', &quot;&quot;, $sprintf ); \n} \n</code></pre>\n" } ]
2018/02/15
[ "https://wordpress.stackexchange.com/questions/294153", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134645/" ]
Is there any hook to change the single product thumbnail? I did search a lot on SO as well as over the internet but no luck. With 'thumbnail' I don't mean changing the size of the current image but I want to completely change/replace the product image (thumbnail) with a new image based on some scenario. ``` public function pn_change_product_image_link( $html, $post_id ){ $url = get_post_meta( $post_id ); $alt = get_post_field( 'post_title', $post_id ) . ' ' . __( 'thumbnail', 'txtdomain' ); $attr = array( 'alt' => $alt ); $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, NULL ); $attr = array_map( 'esc_attr', $attr ); $html = sprintf( '<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/WP_Suspension_logo.svg/2000px-WP_Suspension_logo.svg.png"', esc_url($url) ); foreach ( $attr as $name => $value ) { $html .= " $name=" . '"' . $value . '"'; } $html .= ' />'; return $html; } ``` This is what I'm doing now but it's throwing an error. Filter, Hook: ``` post_thumbnail_html ```
Here's what I believe is an updated version of one of the other answers' comments. This function replaces the width and height attributes, but OP wanted to change the src. I imagine the solution would be similar, except using preg\_replace to replace the src instead. ``` add_action('woocommerce_single_product_image_thumbnail_html','remove_single_product_image_attrs',10,2); function remove_single_product_image_attrs( $sprintf, $post_id ){ return preg_replace( '/(width|height)="\d*"\s/', "", $sprintf ); } ```
294,181
<p>I have noticed Wordpress loves to insert <code>&lt;p&gt;</code> tags everywhere. This can be both helpful and completely annoying...</p> <p>The issue is sometimes i will catch empty <code>&lt;p&gt;</code> tags inserted into the html, which cause a spacing issue (creating more white space on the page..)</p> <p>Instead of disabling the <code>&lt;p&gt;</code> tag styles all together. I would like to set the height of all <code>&lt;p&gt;</code> tags to <code>0px</code> if the <code>&lt;p&gt;</code> tag is empty (has no text inside).</p> <p>Can i do this without jquery or javascript? PHP maybe?</p> <p>If jquery is the only option, you may post this as the answer.</p> <p>Thanks for any help!</p>
[ { "answer_id": 294182, "author": "Wilco", "author_id": 102737, "author_profile": "https://wordpress.stackexchange.com/users/102737", "pm_score": 3, "selected": true, "text": "<p>I always like to use this in my css:</p>\n\n<pre><code>p:empty{\n\n height: 0;\n\n // or \n display: none;\n}\n</code></pre>\n\n<p>Keep in mind that this only removes absolutely empty paragraph tags. If there is a space or anything it will not be targeted.\nMore about the empty selector <a href=\"https://www.w3schools.com/cssref/sel_empty.asp\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 294281, "author": "Chintan Sartape", "author_id": 136987, "author_profile": "https://wordpress.stackexchange.com/users/136987", "pm_score": 0, "selected": false, "text": "<p>What you want to do is instruct the browser to either shrink the height of the element, or merely hide it if there's no content. This can be done with the CSS <code>:empty</code> pseudoelement:</p>\n\n<pre><code>p:empty {\n height: 0;\n}\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>p:empty {\n display: none;\n}\n</code></pre>\n\n<p>Be careful that your other CSS rules don't interfere with or otherwise override this.</p>\n" } ]
2018/02/15
[ "https://wordpress.stackexchange.com/questions/294181", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110570/" ]
I have noticed Wordpress loves to insert `<p>` tags everywhere. This can be both helpful and completely annoying... The issue is sometimes i will catch empty `<p>` tags inserted into the html, which cause a spacing issue (creating more white space on the page..) Instead of disabling the `<p>` tag styles all together. I would like to set the height of all `<p>` tags to `0px` if the `<p>` tag is empty (has no text inside). Can i do this without jquery or javascript? PHP maybe? If jquery is the only option, you may post this as the answer. Thanks for any help!
I always like to use this in my css: ``` p:empty{ height: 0; // or display: none; } ``` Keep in mind that this only removes absolutely empty paragraph tags. If there is a space or anything it will not be targeted. More about the empty selector [here](https://www.w3schools.com/cssref/sel_empty.asp)
294,185
<p>I have an old school user who wants to upload an excel file to our Wordpress page.</p> <p>Basically, Wordpress does not allow this.</p> <p>Upon </p> <p><a href="https://gist.github.com/robwent/e3bf00bafe7a00bc3d0c4dceabde4fca" rel="nofollow noreferrer">https://gist.github.com/robwent/e3bf00bafe7a00bc3d0c4dceabde4fca</a></p> <p>I put the following into functions.php before the end "Includes":</p> <pre><code>function my_custom_mime_types( $mimes ) { // New allowed mime types. $mimes['xls'] = 'application/vnd.ms-excel'; return $mimes; } add_filter( 'upload_mimes', 'my_custom_mime_types', 9999 ); </code></pre> <p>But upon uploading an .xls file I get an error message that due to security this is not allowed (re-translated from my native language).</p> <p>Was this an attempt in the right direction? How can I make this work?</p>
[ { "answer_id": 294198, "author": "sandrodz", "author_id": 115734, "author_profile": "https://wordpress.stackexchange.com/users/115734", "pm_score": 2, "selected": false, "text": "<p>I think the proper filter would be <a href=\"https://developer.wordpress.org/reference/hooks/mime_types/\" rel=\"nofollow noreferrer\">mime_types</a> found <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.2/src/wp-includes/functions.php#L2401\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<pre><code>function wpse294198_mime_types( $mimes ) {\n $mimes['xls|xlsx'] = 'application/vnd.ms-excel';\n return $mimes;\n}\nadd_filter( 'mime_types', 'wpse294198_mime_types' );\n</code></pre>\n\n<p>You can use command line tool <code>file</code> (linux|macOS) to see the mime type, e.g. <code>file --mime-type -b somefile.xls</code></p>\n" }, { "answer_id": 342236, "author": "Sayed Mohd Ali", "author_id": 171223, "author_profile": "https://wordpress.stackexchange.com/users/171223", "pm_score": 0, "selected": false, "text": "<p>I tried the above solution but didn't work for me in the end</p>\n\n<p>I allowed all the mime types via wp-config.php</p>\n\n<pre><code>define( 'ALLOW_UNFILTERED_UPLOADS', true );\n</code></pre>\n\n<p>You can create your custom restriction when the file is submitted. use <code>$_FILES</code> array and put your restriction on the extension of the file and type before upload.</p>\n" }, { "answer_id": 399219, "author": "Sjeiti", "author_id": 32888, "author_profile": "https://wordpress.stackexchange.com/users/32888", "pm_score": 0, "selected": false, "text": "<p>The <code>upload_mimes</code> hook is correct, the mime-type is not (anymore?).</p>\n<p>The following is working for WP 5.8.2</p>\n<pre><code>function my_upload_mimes( $mimes ) {\n return array_merge($mimes, array (\n 'xls' =&gt; 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'xlsx' =&gt; 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'csv' =&gt; 'text/csv'\n ));\n}\nadd_filter( 'upload_mimes', 'my_upload_mimes' );\n</code></pre>\n" } ]
2018/02/15
[ "https://wordpress.stackexchange.com/questions/294185", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28354/" ]
I have an old school user who wants to upload an excel file to our Wordpress page. Basically, Wordpress does not allow this. Upon <https://gist.github.com/robwent/e3bf00bafe7a00bc3d0c4dceabde4fca> I put the following into functions.php before the end "Includes": ``` function my_custom_mime_types( $mimes ) { // New allowed mime types. $mimes['xls'] = 'application/vnd.ms-excel'; return $mimes; } add_filter( 'upload_mimes', 'my_custom_mime_types', 9999 ); ``` But upon uploading an .xls file I get an error message that due to security this is not allowed (re-translated from my native language). Was this an attempt in the right direction? How can I make this work?
I think the proper filter would be [mime\_types](https://developer.wordpress.org/reference/hooks/mime_types/) found [here](https://core.trac.wordpress.org/browser/tags/4.9.2/src/wp-includes/functions.php#L2401). ``` function wpse294198_mime_types( $mimes ) { $mimes['xls|xlsx'] = 'application/vnd.ms-excel'; return $mimes; } add_filter( 'mime_types', 'wpse294198_mime_types' ); ``` You can use command line tool `file` (linux|macOS) to see the mime type, e.g. `file --mime-type -b somefile.xls`
294,186
<p>I want to edit the screen_reader_text in link-template.php Can I do this in a theme so it wont get overwritten on update. It seems a filter is the best option but I cant find documentation on what filter to use.</p> <p>Here is the code I want to change from link-template.php:</p> <pre><code> if ( $GLOBALS['wp_query']-&gt;max_num_pages &gt; 1 ) { $args = wp_parse_args( $args, array( 'mid_size' =&gt; 1, 'prev_text' =&gt; _x( 'Previous', 'previous set of posts' ), 'next_text' =&gt; _x( 'Next', 'next set of posts' ), 'screen_reader_text' =&gt; __( 'Posts navigation' ), ) ); </code></pre> <p>How can I change Posts navigation to something else, via functions or another way?</p>
[ { "answer_id": 294198, "author": "sandrodz", "author_id": 115734, "author_profile": "https://wordpress.stackexchange.com/users/115734", "pm_score": 2, "selected": false, "text": "<p>I think the proper filter would be <a href=\"https://developer.wordpress.org/reference/hooks/mime_types/\" rel=\"nofollow noreferrer\">mime_types</a> found <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.2/src/wp-includes/functions.php#L2401\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<pre><code>function wpse294198_mime_types( $mimes ) {\n $mimes['xls|xlsx'] = 'application/vnd.ms-excel';\n return $mimes;\n}\nadd_filter( 'mime_types', 'wpse294198_mime_types' );\n</code></pre>\n\n<p>You can use command line tool <code>file</code> (linux|macOS) to see the mime type, e.g. <code>file --mime-type -b somefile.xls</code></p>\n" }, { "answer_id": 342236, "author": "Sayed Mohd Ali", "author_id": 171223, "author_profile": "https://wordpress.stackexchange.com/users/171223", "pm_score": 0, "selected": false, "text": "<p>I tried the above solution but didn't work for me in the end</p>\n\n<p>I allowed all the mime types via wp-config.php</p>\n\n<pre><code>define( 'ALLOW_UNFILTERED_UPLOADS', true );\n</code></pre>\n\n<p>You can create your custom restriction when the file is submitted. use <code>$_FILES</code> array and put your restriction on the extension of the file and type before upload.</p>\n" }, { "answer_id": 399219, "author": "Sjeiti", "author_id": 32888, "author_profile": "https://wordpress.stackexchange.com/users/32888", "pm_score": 0, "selected": false, "text": "<p>The <code>upload_mimes</code> hook is correct, the mime-type is not (anymore?).</p>\n<p>The following is working for WP 5.8.2</p>\n<pre><code>function my_upload_mimes( $mimes ) {\n return array_merge($mimes, array (\n 'xls' =&gt; 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'xlsx' =&gt; 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'csv' =&gt; 'text/csv'\n ));\n}\nadd_filter( 'upload_mimes', 'my_upload_mimes' );\n</code></pre>\n" } ]
2018/02/15
[ "https://wordpress.stackexchange.com/questions/294186", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14416/" ]
I want to edit the screen\_reader\_text in link-template.php Can I do this in a theme so it wont get overwritten on update. It seems a filter is the best option but I cant find documentation on what filter to use. Here is the code I want to change from link-template.php: ``` if ( $GLOBALS['wp_query']->max_num_pages > 1 ) { $args = wp_parse_args( $args, array( 'mid_size' => 1, 'prev_text' => _x( 'Previous', 'previous set of posts' ), 'next_text' => _x( 'Next', 'next set of posts' ), 'screen_reader_text' => __( 'Posts navigation' ), ) ); ``` How can I change Posts navigation to something else, via functions or another way?
I think the proper filter would be [mime\_types](https://developer.wordpress.org/reference/hooks/mime_types/) found [here](https://core.trac.wordpress.org/browser/tags/4.9.2/src/wp-includes/functions.php#L2401). ``` function wpse294198_mime_types( $mimes ) { $mimes['xls|xlsx'] = 'application/vnd.ms-excel'; return $mimes; } add_filter( 'mime_types', 'wpse294198_mime_types' ); ``` You can use command line tool `file` (linux|macOS) to see the mime type, e.g. `file --mime-type -b somefile.xls`
294,203
<p>I keep all hooks in one file, and the functions are organized in their respective classes (different auto-loaded files).</p> <p>Looking for a standard way to document that a function's sole purpose is to be called on 'init' for example.</p> <p>Currently using <code>@see 'init'</code></p> <p>Thanks!</p> <h1>Example Code</h1> <p><strong>hooks.php</strong></p> <pre class="lang-php prettyprint-override"><code>add_action( 'init', 'remove_image_sizes' ); </code></pre> <p><strong>functions.php</strong></p> <pre class="lang-php prettyprint-override"><code>/** * Removes image sizes added by mistake prior to 1.6.18 * * @since 1.6.18 * @see 'init' * @return void */ function remove_image_sizes() { remove_image_size( 'foo' ); remove_image_size( 'bar' ); } </code></pre>
[ { "answer_id": 294211, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>Function doc block should document what it does, what it might be useful for, but not who uses it. It makes sense to document that it was designed with hook X in mind but that is it.</p>\n\n<p>Think of unit testing. In that context you are likely to call the function by itself without doing the whole core initialization, which means that a description tying the function to the init hook, will be at least misleading.</p>\n\n<p>The style you are trying to use will also force you to change documentation while changing irrelevant code, like if you will decide to move the call to <code>wp_loaded</code> instead of <code>init</code></p>\n" }, { "answer_id": 387903, "author": "Simon Kane", "author_id": 206150, "author_profile": "https://wordpress.stackexchange.com/users/206150", "pm_score": 0, "selected": false, "text": "<p>I disagree with the previous answer.\nIt appears that the respondent does not develop for WordPress:\n&quot;Think of unit testing. In that context you are likely to call the function by itself&quot;\nThis, obviously, is not feasible for the overwhelming majority of WP code.</p>\n<p>However, the &quot;move the call&quot; statement is, although infrequent because almost all hooks are designed to perform a very specific act, a valid concern. What is more typical is that an existing filter will end up being used by multiple hook IDs, as some of the IDs are dynamically generated, but statically referenced. The case where it is dynamic on both sides is beyond any kind of documentation parser's abilities.</p>\n<p>I think the correct solution is something that parses add_action and add_filter calls into references of some kind like maybe @hook_for (I am just getting into this phpdoc stuff, so bear with me). This may be in a docblock, &quot;special comment&quot;, or even just some kind of helper in doxygen or the like (but manual access is also needed to cover edge cases).</p>\n<p>What I want is for doxygen or phpdoc to gather these @hook_for references into caller/callee lists like they do for normal function references - but obviously in a separate part of the output. Knowing which hooks a plugin or theme uses, and being able to 1-click to the code would be an amazing thing to have.</p>\n<p>Now that I have invented a new &quot;@&quot; tag, hopefully someone will come along and say &quot;that already exists - use this&quot;. I've looked at @see and @link, but not in depth -- maybe they are the answer? But, for the best results, we still need them to be auto-generated by something in the pre-processor (the add_filter/add_action parser I propose).</p>\n" }, { "answer_id": 391332, "author": "XedinUnknown", "author_id": 64825, "author_profile": "https://wordpress.stackexchange.com/users/64825", "pm_score": 1, "selected": false, "text": "<h2>Invoking a Hook</h2>\n<p>If you want to document the usage of a hook that you are invoking somewhere, i.e. things that hook <em>handlers</em> have to be aware of, then there is a <a href=\"https://make.wordpress.org/core/handbook/best-practices/inline-documentation-standards/php/#4-hooks-actions-and-filters\" rel=\"nofollow noreferrer\">hook documentation standard</a>.</p>\n<h2>Using a Hook</h2>\n<p>If your function or method uses a hook, either by invoking or handling it, you can simply mention that with PHPDoc's standard syntax. This is because a WordPress hook is not a <a href=\"https://docs.phpdoc.org/3.0/guide/getting-started/what-is-a-docblock.html#what-can-be-documented-in-your-source-code\" rel=\"nofollow noreferrer\">Structural Element</a> that vanilla PHPDoc will look for. Let's look at the <a href=\"https://docs.phpdoc.org/3.0/guide/references/phpdoc/tags/see.html#see\" rel=\"nofollow noreferrer\"><code>@see</code></a> tag syntax:</p>\n<pre><code>@see [URI | FQSEN] [&lt;description&gt;]\n</code></pre>\n<p>This can be interpreted the following way:</p>\n<blockquote>\n<p>The <code>@see</code> tag MUST be followed by a URI or the FQSEN, OPTIONALLY followed by the description. The <code>URI</code> and <code>FQSEN</code> components determine where the link points to, whereas the <code>description</code> component determines the text of the link.</p>\n</blockquote>\n<p>Thus, a good way to document WP hooks used in your function is like this:</p>\n<pre><code>/**\n * Summary.\n *\n * @see https://developer.wordpress.org/reference/hooks/plugins_loaded/ plugins_loaded\n */\nfunction myFunc() {}\n</code></pre>\n" } ]
2018/02/15
[ "https://wordpress.stackexchange.com/questions/294203", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78828/" ]
I keep all hooks in one file, and the functions are organized in their respective classes (different auto-loaded files). Looking for a standard way to document that a function's sole purpose is to be called on 'init' for example. Currently using `@see 'init'` Thanks! Example Code ============ **hooks.php** ```php add_action( 'init', 'remove_image_sizes' ); ``` **functions.php** ```php /** * Removes image sizes added by mistake prior to 1.6.18 * * @since 1.6.18 * @see 'init' * @return void */ function remove_image_sizes() { remove_image_size( 'foo' ); remove_image_size( 'bar' ); } ```
Function doc block should document what it does, what it might be useful for, but not who uses it. It makes sense to document that it was designed with hook X in mind but that is it. Think of unit testing. In that context you are likely to call the function by itself without doing the whole core initialization, which means that a description tying the function to the init hook, will be at least misleading. The style you are trying to use will also force you to change documentation while changing irrelevant code, like if you will decide to move the call to `wp_loaded` instead of `init`
294,223
<p>I am stumped on something I have been working on and would really appreciate any help you can offer.</p> <p>The code below is what elements are to be displayed on a job note. It currently has the users avatar, username, date created and the comment. Both users and administrators(co-workers) can use the notes. If the username of the comment is Administrator then next to it display "- expert". But if the username of the comment is not Administrator role then it will not display anything next to it.</p> <pre><code>&lt;?php ?&gt;&lt;div itemscope itemtype="https://schema.org/Comment"&gt; &lt;div class="gv-note-author-details" itemscope itemtype="https://schema.org/Person"&gt; &lt;div class="gv-note-avatar" itemprop="image"&gt;{avatar}&lt;/div&gt; &lt;h6 class="gv-note-author" itemprop="name"&gt;{user_name} &lt;?php if { echo "Echo expert title here";} else { "echo nothing"}}?&gt;&lt;/h6&gt; &lt;/div&gt; &lt;span class="gv-note-added-on" itemprop="dateCreated" datetime="{date_created}"&gt;{added_on}&lt;/span&gt; &lt;div class="gv-note-content" itemprop="comment"&gt;{value}&lt;/div&gt; </code></pre> <p></p> <p>The only thing I see online that references this is get_current_user but I don't want it to get current user. I want it to simple check if username is Administrator then echo "- expert"; else echo "echo nothing";</p> <p>Note {user_name} is display name of user</p>
[ { "answer_id": 294227, "author": "terminator", "author_id": 55034, "author_profile": "https://wordpress.stackexchange.com/users/55034", "pm_score": 0, "selected": false, "text": "<p>I think this might work for you </p>\n\n<pre><code>$username = \"terminator\";\n$user = get_user_by('login',$username); \nif(in_array('administrator',$user-&gt;roles )){ \n echo \"Echo expert\";\n}else{\n echo \"nothing\";\n}\n</code></pre>\n\n<p>Let me know how it goes\nthanks</p>\n" }, { "answer_id": 294229, "author": "BBackerry", "author_id": 136935, "author_profile": "https://wordpress.stackexchange.com/users/136935", "pm_score": 2, "selected": false, "text": "<p>@terminator answer might work but there's no need to create an array and use array_intersect I think since you're only looking for one role. This might be more comprehensible:</p>\n\n<pre><code>$current_user = wp_get_current_user();\n$roles = (array) $current_user-&gt;roles;\nif (in_array('administrator', $roles) { /* echo whatever */ }\n</code></pre>\n\n<p>Don't forget to check that 'administrator' is acutally the role key you want.</p>\n" }, { "answer_id": 294236, "author": "Beee", "author_id": 103402, "author_profile": "https://wordpress.stackexchange.com/users/103402", "pm_score": 1, "selected": false, "text": "<p>Both Bbackerry and terminator didn't read properly. The OP asked: \"I want it to simple check if username is Administrator then echo \"- expert\"; else echo \"echo nothing\";\". Which is the following code:</p>\n\n<pre><code>$current_user = wp_get_current_user();\nif ( $current_user-&gt;user_login == 'Administrator' ) {\n echo '- expert';\n} else {\n echo \"echo nothing\";\n}\n</code></pre>\n" } ]
2018/02/15
[ "https://wordpress.stackexchange.com/questions/294223", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/132977/" ]
I am stumped on something I have been working on and would really appreciate any help you can offer. The code below is what elements are to be displayed on a job note. It currently has the users avatar, username, date created and the comment. Both users and administrators(co-workers) can use the notes. If the username of the comment is Administrator then next to it display "- expert". But if the username of the comment is not Administrator role then it will not display anything next to it. ``` <?php ?><div itemscope itemtype="https://schema.org/Comment"> <div class="gv-note-author-details" itemscope itemtype="https://schema.org/Person"> <div class="gv-note-avatar" itemprop="image">{avatar}</div> <h6 class="gv-note-author" itemprop="name">{user_name} <?php if { echo "Echo expert title here";} else { "echo nothing"}}?></h6> </div> <span class="gv-note-added-on" itemprop="dateCreated" datetime="{date_created}">{added_on}</span> <div class="gv-note-content" itemprop="comment">{value}</div> ``` The only thing I see online that references this is get\_current\_user but I don't want it to get current user. I want it to simple check if username is Administrator then echo "- expert"; else echo "echo nothing"; Note {user\_name} is display name of user
@terminator answer might work but there's no need to create an array and use array\_intersect I think since you're only looking for one role. This might be more comprehensible: ``` $current_user = wp_get_current_user(); $roles = (array) $current_user->roles; if (in_array('administrator', $roles) { /* echo whatever */ } ``` Don't forget to check that 'administrator' is acutally the role key you want.
294,263
<p>Hey guys i'm trying to change the blog title to an image.</p> <p><a href="https://i.stack.imgur.com/cOx1R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cOx1R.png" alt=""></a></p> <p>This is what I'm trying to achieve</p> <p><a href="https://i.stack.imgur.com/VrqGI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VrqGI.jpg" alt=""></a></p> <p>I tried adding this code to the css and it's working.</p> <pre><code>.rh-content { text-indent: -9999px; background: url(http:file-location.png) 10px 10px no-repeat; /* height: 100%; */ } </code></pre> <p>But this is the result</p> <p><a href="https://i.stack.imgur.com/wZmgO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wZmgO.png" alt=""></a></p> <p>The image is not showing enough. Also I want to add it to the functions.php in my child theme. i Tried this code</p> <pre><code>add_filter('the_title', function($title){ $title = '&lt;img src="'. get_template_directory_uri() .'/images/blah.png"&gt;' . $title; return $title; }); ?&gt; </code></pre> <p>but this is the result. This is what i'm seeing when i add the filter function <a href="https://i.stack.imgur.com/aN2V0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aN2V0.png" alt=""></a></p> <p>This is the raw code</p> <pre><code>&lt;div class="rh-content"&gt; &lt;?php if (is_author() || is_archive() || is_day() || is_tag() || is_category() || is_month() || is_day() || is_year()): ?&gt; &lt;h1 style="&lt;?php echo esc_attr($styles_title); ?&gt;"&gt; &lt;?php if (is_category()): ?&gt; &lt;?php echo single_cat_title("", true); ?&gt; &lt;?php elseif(is_tag()): ?&gt; &lt;?php echo single_tag_title("", true); ?&gt; &lt;?php elseif(is_day()): ?&gt; &lt;?php echo get_the_date('F dS Y'); ?&gt; &lt;?php elseif(is_month()): ?&gt; &lt;?php echo get_the_date('Y, F'); ?&gt; &lt;?php elseif(is_year()): ?&gt; &lt;?php echo get_the_date('Y'); ?&gt; &lt;?php elseif(is_author()): ?&gt; &lt;?php $userdata = get_userdata($GLOBALS['author']); ?&gt; &lt;?php echo esc_html__("Articles posted by", 'thebuilders'); ?&gt; "&lt;?php echo esc_attr($userdata-&gt;first_name)." ".esc_attr($userdata-&gt;last_name); ?&gt;" &lt;?php else: ?&gt; &lt;?php echo esc_html__("Posts", 'thebuilders'); ?&gt; &lt;?php endif ?&gt; &lt;/h1&gt; &lt;div style="&lt;?php echo esc_attr($styles_breadcrumbs); ?&gt;" class="nz-breadcrumbs nz-clearfix"&gt;&lt;?php thebuilders_ninzio_breadcrumbs(); ?&gt;&lt;/div&gt; &lt;?php else: ?&gt; &lt;?php if (isset($GLOBALS['thebuilders_ninzio']['blog-title']) &amp;&amp; !empty($GLOBALS['thebuilders_ninzio']['blog-title'])): ?&gt; &lt;h1 style="&lt;?php echo esc_attr($styles_title); ?&gt;"&gt;&lt;?php echo esc_attr($GLOBALS['thebuilders_ninzio']['blog-title']); ?&gt;&lt;/h1&gt; &lt;?php else: ?&gt; &lt;h1 style="&lt;?php echo esc_attr($styles_title); ?&gt;"&gt;&lt;?php echo esc_html__("Posts", 'thebuilders'); ?&gt;&lt;/h1&gt; &lt;?php endif ?&gt; &lt;div style="&lt;?php echo esc_attr($styles_breadcrumbs); ?&gt;" class="nz-breadcrumbs nz-clearfix"&gt;&lt;?php thebuilders_ninzio_breadcrumbs(); ?&gt;&lt;/div&gt; &lt;?php endif; ?&gt; &lt;/div&gt; </code></pre> <p>This is the url link. <a href="https://harborllc.wpengine.com/blogs/" rel="nofollow noreferrer">https://harborllc.wpengine.com/blogs/</a></p> <p>Thank you very much guys</p>
[ { "answer_id": 294250, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>The straight answer is \"no\" and it is also inpossible to have such a thing as code always depends on some DB format, and you can not just change the code without the DB.</p>\n\n<p>What happens when you upgrade over several releases will depend on the quality of the plugins and the testings being done to them. You can almost always be sure that one \"step\" upgrades were tested but it is much more problematic to assume that multiple \"steps\" upgrade was tested well.</p>\n\n<p>As always, the best thing is to do the upgrades on a staging enviroment, and do some sanity tests before doing anything on production.</p>\n" }, { "answer_id": 294252, "author": "Malay Solanki", "author_id": 130744, "author_profile": "https://wordpress.stackexchange.com/users/130744", "pm_score": 0, "selected": false, "text": "<p>There is no such rule. Plugin update may contain database changes or may not contain. Generally all plugin update code written on WordPress init hook. Once your WordPress will init all plugin update code will get executed</p>\n" } ]
2018/02/16
[ "https://wordpress.stackexchange.com/questions/294263", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
Hey guys i'm trying to change the blog title to an image. [![](https://i.stack.imgur.com/cOx1R.png)](https://i.stack.imgur.com/cOx1R.png) This is what I'm trying to achieve [![](https://i.stack.imgur.com/VrqGI.jpg)](https://i.stack.imgur.com/VrqGI.jpg) I tried adding this code to the css and it's working. ``` .rh-content { text-indent: -9999px; background: url(http:file-location.png) 10px 10px no-repeat; /* height: 100%; */ } ``` But this is the result [![](https://i.stack.imgur.com/wZmgO.png)](https://i.stack.imgur.com/wZmgO.png) The image is not showing enough. Also I want to add it to the functions.php in my child theme. i Tried this code ``` add_filter('the_title', function($title){ $title = '<img src="'. get_template_directory_uri() .'/images/blah.png">' . $title; return $title; }); ?> ``` but this is the result. This is what i'm seeing when i add the filter function [![](https://i.stack.imgur.com/aN2V0.png)](https://i.stack.imgur.com/aN2V0.png) This is the raw code ``` <div class="rh-content"> <?php if (is_author() || is_archive() || is_day() || is_tag() || is_category() || is_month() || is_day() || is_year()): ?> <h1 style="<?php echo esc_attr($styles_title); ?>"> <?php if (is_category()): ?> <?php echo single_cat_title("", true); ?> <?php elseif(is_tag()): ?> <?php echo single_tag_title("", true); ?> <?php elseif(is_day()): ?> <?php echo get_the_date('F dS Y'); ?> <?php elseif(is_month()): ?> <?php echo get_the_date('Y, F'); ?> <?php elseif(is_year()): ?> <?php echo get_the_date('Y'); ?> <?php elseif(is_author()): ?> <?php $userdata = get_userdata($GLOBALS['author']); ?> <?php echo esc_html__("Articles posted by", 'thebuilders'); ?> "<?php echo esc_attr($userdata->first_name)." ".esc_attr($userdata->last_name); ?>" <?php else: ?> <?php echo esc_html__("Posts", 'thebuilders'); ?> <?php endif ?> </h1> <div style="<?php echo esc_attr($styles_breadcrumbs); ?>" class="nz-breadcrumbs nz-clearfix"><?php thebuilders_ninzio_breadcrumbs(); ?></div> <?php else: ?> <?php if (isset($GLOBALS['thebuilders_ninzio']['blog-title']) && !empty($GLOBALS['thebuilders_ninzio']['blog-title'])): ?> <h1 style="<?php echo esc_attr($styles_title); ?>"><?php echo esc_attr($GLOBALS['thebuilders_ninzio']['blog-title']); ?></h1> <?php else: ?> <h1 style="<?php echo esc_attr($styles_title); ?>"><?php echo esc_html__("Posts", 'thebuilders'); ?></h1> <?php endif ?> <div style="<?php echo esc_attr($styles_breadcrumbs); ?>" class="nz-breadcrumbs nz-clearfix"><?php thebuilders_ninzio_breadcrumbs(); ?></div> <?php endif; ?> </div> ``` This is the url link. <https://harborllc.wpengine.com/blogs/> Thank you very much guys
The straight answer is "no" and it is also inpossible to have such a thing as code always depends on some DB format, and you can not just change the code without the DB. What happens when you upgrade over several releases will depend on the quality of the plugins and the testings being done to them. You can almost always be sure that one "step" upgrades were tested but it is much more problematic to assume that multiple "steps" upgrade was tested well. As always, the best thing is to do the upgrades on a staging enviroment, and do some sanity tests before doing anything on production.
294,318
<p>I have the following bit of code that is called from the the <code>the_post</code> hook. This code works fine on one of our live sites, but I'm trying to develop the plugin further locally and this is no longer working.</p> <pre><code>public function fetch_post_data( $post ) { $post-&gt;post_content = 'This is a test.'; } add_action('the_post', 'fetch_post_data'); </code></pre> <p>This is of course very simplified, but it gets the point across. I am modifying the post object, attempting to alter the content before it is output on the page. Like I said, this is working on our live sites just fine, but for some reason isn't working on my local development server. The crazy thing is that if I <code>var_dump($post);</code> I can see that the <code>$post</code> object has indeed been updated with my new content. Is there a better way to do this and that's the reason this isn't working? Any help would be greatly appreciated.</p> <p>I know that this code works, as it's being used on a live site already, and I know it's modifying the object, because when I dump it, it displays the new value correctly, and I know other people are doing this by googling (IE <a href="https://stackoverflow.com/questions/30007523/modifying-post-post-content-in-wordpress">https://stackoverflow.com/questions/30007523/modifying-post-post-content-in-wordpress</a>). I'm just confused on why when WP outputs the content on the local server, it isn't taking the updated object into account.</p> <p>If I issue the following, the first line outputs my new, modified content, and the second line outputs the old, unmodified content. Why aren't they the same?</p> <pre><code>var_dump($post-&gt;post_content); echo get_the_content(); </code></pre>
[ { "answer_id": 294319, "author": "Kevin", "author_id": 27041, "author_profile": "https://wordpress.stackexchange.com/users/27041", "pm_score": 0, "selected": false, "text": "<p>I was able to solve this with the following. I don't know if this is proper, and I don't really understand why it's necessary, but it is doing what I need it to do now:</p>\n\n<pre><code>public function fetch_post_data($post) {\n add_filter( 'the_title', function( $title) use ($post) {\n if(is_singular() &amp;&amp; in_the_loop() &amp;&amp; is_main_query() &amp;&amp; $post-&gt;post_type === 'my_cpt') {\n return $post-&gt;post_title;\n }\n return $title;\n } );\n\n add_filter( 'the_content', function( $content ) use ($post) {\n if(is_singular() &amp;&amp; in_the_loop() &amp;&amp; is_main_query() &amp;&amp; $post-&gt;post_type === 'my_cpt') {\n return $post-&gt;post_content;\n }\n return $content;\n } );\n}\n</code></pre>\n\n<p>If anyone has any input on why this is now necessary, I would love to hear it.</p>\n" }, { "answer_id": 294334, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 1, "selected": false, "text": "<p><code>get_the_content()</code> doesn't actually return the <code>post_content</code> property from the global <code>$post</code> object. Instead it returns the first page of the global variable <code>$pages</code>, which is set before <code>the_post</code> hook is fired. See <a href=\"https://core.trac.wordpress.org/browser/tags/4.9/src/wp-includes/post-template.php#L287\" rel=\"nofollow noreferrer\">L287 of wp-includes/post-template</a>.</p>\n\n<p>To reset the <code>$pages</code> global, you can use the <code>setup_postdata()</code> method from the <code>WP_Query</code> object passed from the <code>the_post</code> hook.</p>\n\n<pre><code>add_action( 'the_post', 'wpse_the_post', 10, 2 );\nfunction wpse_the_post( $post, $query ) {\n $post-&gt;post_title = 'Foo';\n $post-&gt;post_content = 'Yolo';\n\n //* To prevent infinite loop\n remove_action( 'the_post', 'wpse_the_post' );\n $query-&gt;setup_postdata( $post );\n add_action( 'the_post', 'wpse_the_post', 10, 2 );\n}\n</code></pre>\n\n<p>This is kind of backwards since you're then setting up the post data twice. But if you're intent on using <code>the_post</code> hook... </p>\n\n<p>I'd use two different filters instead (<code>the_title</code> and <code>the_content</code>).</p>\n" } ]
2018/02/16
[ "https://wordpress.stackexchange.com/questions/294318", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27041/" ]
I have the following bit of code that is called from the the `the_post` hook. This code works fine on one of our live sites, but I'm trying to develop the plugin further locally and this is no longer working. ``` public function fetch_post_data( $post ) { $post->post_content = 'This is a test.'; } add_action('the_post', 'fetch_post_data'); ``` This is of course very simplified, but it gets the point across. I am modifying the post object, attempting to alter the content before it is output on the page. Like I said, this is working on our live sites just fine, but for some reason isn't working on my local development server. The crazy thing is that if I `var_dump($post);` I can see that the `$post` object has indeed been updated with my new content. Is there a better way to do this and that's the reason this isn't working? Any help would be greatly appreciated. I know that this code works, as it's being used on a live site already, and I know it's modifying the object, because when I dump it, it displays the new value correctly, and I know other people are doing this by googling (IE <https://stackoverflow.com/questions/30007523/modifying-post-post-content-in-wordpress>). I'm just confused on why when WP outputs the content on the local server, it isn't taking the updated object into account. If I issue the following, the first line outputs my new, modified content, and the second line outputs the old, unmodified content. Why aren't they the same? ``` var_dump($post->post_content); echo get_the_content(); ```
`get_the_content()` doesn't actually return the `post_content` property from the global `$post` object. Instead it returns the first page of the global variable `$pages`, which is set before `the_post` hook is fired. See [L287 of wp-includes/post-template](https://core.trac.wordpress.org/browser/tags/4.9/src/wp-includes/post-template.php#L287). To reset the `$pages` global, you can use the `setup_postdata()` method from the `WP_Query` object passed from the `the_post` hook. ``` add_action( 'the_post', 'wpse_the_post', 10, 2 ); function wpse_the_post( $post, $query ) { $post->post_title = 'Foo'; $post->post_content = 'Yolo'; //* To prevent infinite loop remove_action( 'the_post', 'wpse_the_post' ); $query->setup_postdata( $post ); add_action( 'the_post', 'wpse_the_post', 10, 2 ); } ``` This is kind of backwards since you're then setting up the post data twice. But if you're intent on using `the_post` hook... I'd use two different filters instead (`the_title` and `the_content`).
294,321
<p>I'm trying to build a gutenberg block (via plugin) that interfaces with a third-party api via credentials. I'm unsure how to, or even if I can, access a plugin's settings in gutenberg in order to grab a potential credentials field for use in the block. (I understand there's potential to put something in the editor's sidebar, but I need a persistent global setting that doesn't have to be set with every block.) Am I missing something in the documentation or is this not possible yet?</p>
[ { "answer_id": 300042, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 4, "selected": true, "text": "<p>The WordPress way to access PHP variables with JavaScript is to use <a href=\"https://developer.wordpress.org/reference/functions/wp_localize_script/\" rel=\"nofollow noreferrer\"><code>wp_localize_script()</code></a>.</p>\n\n<pre><code>function wpse_enqueue_scripts(){\n wp_enqueue_script( 'wpse', PATH_TO . 'script.js' );\n wp_localize_script( 'wpse', 'credentials', $credentials );\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_enqueue_scripts' );\n</code></pre>\n\n<p>Then in your JavaScript, you can access the credentials like</p>\n\n<pre><code>console.log( credentials );\n</code></pre>\n" }, { "answer_id": 344733, "author": "jshwlkr", "author_id": 98703, "author_profile": "https://wordpress.stackexchange.com/users/98703", "pm_score": 2, "selected": false, "text": "<p>Now, I believe <code>wp_add_inline_script</code> is maybe the better option.\n(<a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_script/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_add_inline_script/</a>)</p>\n" } ]
2018/02/16
[ "https://wordpress.stackexchange.com/questions/294321", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98703/" ]
I'm trying to build a gutenberg block (via plugin) that interfaces with a third-party api via credentials. I'm unsure how to, or even if I can, access a plugin's settings in gutenberg in order to grab a potential credentials field for use in the block. (I understand there's potential to put something in the editor's sidebar, but I need a persistent global setting that doesn't have to be set with every block.) Am I missing something in the documentation or is this not possible yet?
The WordPress way to access PHP variables with JavaScript is to use [`wp_localize_script()`](https://developer.wordpress.org/reference/functions/wp_localize_script/). ``` function wpse_enqueue_scripts(){ wp_enqueue_script( 'wpse', PATH_TO . 'script.js' ); wp_localize_script( 'wpse', 'credentials', $credentials ); } add_action( 'wp_enqueue_scripts', 'wpse_enqueue_scripts' ); ``` Then in your JavaScript, you can access the credentials like ``` console.log( credentials ); ```
294,324
<p>i want to make a little Header with the 3 recent thumbnails in different sizes and start my loop with the 4th recent posts, can someone give me a function for that please? please no widgets i want to make it raw and get more into webdesign.</p> <p>U can see how it looks on my page: <a href="http://web91.s67.goserver.host/" rel="nofollow noreferrer">http://web91.s67.goserver.host/</a></p> <p>the 3 grey boxes should contain the thumbnails of the 3 recent posts and the the loop underneath should start then with the 4th post (2 different thumbnail sizes)</p> <p>I already know how to define the sizes in the functions which looks like this right now:</p> <pre><code>// Add featured image support add_theme_support(‘post-thumbnails’); add_image_size(‘small-thumbnail’, 600, 330, true); add_image_size(‘big-thumbnail’, 600, 661, array(‘left’, ‘center’)); </code></pre> <p>but i have no idea how to implement the thumbnails in the right sizes into the 3 grey boxes and how to start with the 4th post underneath</p> <p>thank you!</p>
[ { "answer_id": 300042, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 4, "selected": true, "text": "<p>The WordPress way to access PHP variables with JavaScript is to use <a href=\"https://developer.wordpress.org/reference/functions/wp_localize_script/\" rel=\"nofollow noreferrer\"><code>wp_localize_script()</code></a>.</p>\n\n<pre><code>function wpse_enqueue_scripts(){\n wp_enqueue_script( 'wpse', PATH_TO . 'script.js' );\n wp_localize_script( 'wpse', 'credentials', $credentials );\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_enqueue_scripts' );\n</code></pre>\n\n<p>Then in your JavaScript, you can access the credentials like</p>\n\n<pre><code>console.log( credentials );\n</code></pre>\n" }, { "answer_id": 344733, "author": "jshwlkr", "author_id": 98703, "author_profile": "https://wordpress.stackexchange.com/users/98703", "pm_score": 2, "selected": false, "text": "<p>Now, I believe <code>wp_add_inline_script</code> is maybe the better option.\n(<a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_script/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_add_inline_script/</a>)</p>\n" } ]
2018/02/16
[ "https://wordpress.stackexchange.com/questions/294324", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137014/" ]
i want to make a little Header with the 3 recent thumbnails in different sizes and start my loop with the 4th recent posts, can someone give me a function for that please? please no widgets i want to make it raw and get more into webdesign. U can see how it looks on my page: <http://web91.s67.goserver.host/> the 3 grey boxes should contain the thumbnails of the 3 recent posts and the the loop underneath should start then with the 4th post (2 different thumbnail sizes) I already know how to define the sizes in the functions which looks like this right now: ``` // Add featured image support add_theme_support(‘post-thumbnails’); add_image_size(‘small-thumbnail’, 600, 330, true); add_image_size(‘big-thumbnail’, 600, 661, array(‘left’, ‘center’)); ``` but i have no idea how to implement the thumbnails in the right sizes into the 3 grey boxes and how to start with the 4th post underneath thank you!
The WordPress way to access PHP variables with JavaScript is to use [`wp_localize_script()`](https://developer.wordpress.org/reference/functions/wp_localize_script/). ``` function wpse_enqueue_scripts(){ wp_enqueue_script( 'wpse', PATH_TO . 'script.js' ); wp_localize_script( 'wpse', 'credentials', $credentials ); } add_action( 'wp_enqueue_scripts', 'wpse_enqueue_scripts' ); ``` Then in your JavaScript, you can access the credentials like ``` console.log( credentials ); ```
294,327
<p>I have seen the token %1$ and similar ones more often in the WordPress code lately, but I can't figure out what it means. Here an example:</p> <pre><code>sprintf( __( '%1$s is deprecated. Use %2$s instead.' ), </code></pre> <p>Does anyone know what it means?</p>
[ { "answer_id": 294330, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 3, "selected": false, "text": "<p>It's not a WordPress thing, it's a PHP thing. <code>%1$s</code>, <code>%2$s</code>, etc., are placeholders for variables in a formatted string returned by <a href=\"https://secure.php.net/sprintf\" rel=\"noreferrer\"><code>sprintf()</code></a> (or printed by <a href=\"https://secure.php.net/printf\" rel=\"noreferrer\"><code>printf()</code></a>).</p>\n\n<p>The <code>1$</code> indicates it's the <em>first</em> variable, <code>2$</code> would be the second, and so forth. The <code>s</code> indicates it's a <em>string</em> variable. Other options exist (eg, <code>d</code> would indicate an integer).</p>\n\n<p>The example you give is incomplete: it's certainly something like this in its entirety:</p>\n\n<pre><code>sprintf( __( '%1$s is deprecated. Use %2$s instead.' ),\n$string_1,\n$string_2 );\n</code></pre>\n" }, { "answer_id": 294332, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 5, "selected": true, "text": "<p>Read the <a href=\"http://php.net/manual/en/function.sprintf.php\" rel=\"noreferrer\">PHP docs on sprintf()</a>.</p>\n\n<ul>\n<li><code>%s</code> is just a placeholder for a string</li>\n<li><code>%d</code> is just a placeholder for a number</li>\n</ul>\n\n<p>So an example of sprintf would look like this:</p>\n\n<pre><code>$variable = sprintf(\n 'The %s ran down the %s', // String with placeholders\n 'dog', // Placed in the first %s placeholder\n 'street' // Placed in the second %s placeholder\n);\n</code></pre>\n\n<p>Which will return a string to our variable <code>$variable</code>:</p>\n\n<blockquote>\n <p>The <strong>dog</strong> ran down the <strong>street</strong></p>\n</blockquote>\n\n<p>By numbering the placeholders it's both a developer-friendly way to quickly tell which following string will be placed where. It also allows us to reuse a string. Let's take another example with numbered placeholders:</p>\n\n<pre><code>$variable = sprintf(\n 'The %1$s ran down the %2$s. The %2$s was made of %3$s', // String with placeholders\n 'dog', // Will always be used in %1$s placeholder\n 'street', // Will always be used in %2$s placeholder\n 'gravel' // Will always be used in %3$s placeholder\n);\n</code></pre>\n\n<p>Which will return a string to our variable <code>$variable</code>:</p>\n\n<blockquote>\n <p>The <strong>dog</strong> ran down the <strong>street</strong>. The <strong>street</strong> was made of <strong>gravel</strong></p>\n</blockquote>\n\n<p>Finally, the <a href=\"https://codex.wordpress.org/I18n_for_WordPress_Developers\" rel=\"noreferrer\"><code>__()</code></a> function let's us translate strings passed to it. By passing <code>__()</code> placeholders, and then passing that whole string to <code>sprintf()</code>, we can translate whatever is passed to the translating function allowing us to make our string and application a bit more dynamic.</p>\n" } ]
2018/02/16
[ "https://wordpress.stackexchange.com/questions/294327", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136032/" ]
I have seen the token %1$ and similar ones more often in the WordPress code lately, but I can't figure out what it means. Here an example: ``` sprintf( __( '%1$s is deprecated. Use %2$s instead.' ), ``` Does anyone know what it means?
Read the [PHP docs on sprintf()](http://php.net/manual/en/function.sprintf.php). * `%s` is just a placeholder for a string * `%d` is just a placeholder for a number So an example of sprintf would look like this: ``` $variable = sprintf( 'The %s ran down the %s', // String with placeholders 'dog', // Placed in the first %s placeholder 'street' // Placed in the second %s placeholder ); ``` Which will return a string to our variable `$variable`: > > The **dog** ran down the **street** > > > By numbering the placeholders it's both a developer-friendly way to quickly tell which following string will be placed where. It also allows us to reuse a string. Let's take another example with numbered placeholders: ``` $variable = sprintf( 'The %1$s ran down the %2$s. The %2$s was made of %3$s', // String with placeholders 'dog', // Will always be used in %1$s placeholder 'street', // Will always be used in %2$s placeholder 'gravel' // Will always be used in %3$s placeholder ); ``` Which will return a string to our variable `$variable`: > > The **dog** ran down the **street**. The **street** was made of **gravel** > > > Finally, the [`__()`](https://codex.wordpress.org/I18n_for_WordPress_Developers) function let's us translate strings passed to it. By passing `__()` placeholders, and then passing that whole string to `sprintf()`, we can translate whatever is passed to the translating function allowing us to make our string and application a bit more dynamic.
294,352
<p>I am trying post submit on front end. All works without thumbnail uploading and setting. Here is my html form.</p> <pre><code>&lt;form method="post" action=""&gt; &lt;input type="text" name="title"&gt; &lt;textarea name="content"&gt;&lt;/textarea&gt; &lt;input type="file" name="thumbnail"&gt; &lt;input type="submit" name="submit"&gt; &lt;/form&gt; </code></pre> <p>And here is my php code.</p> <pre><code>&lt;?php if (isset($_POST['submit'])) { global $wpdb; require_once ABSPATH . 'wp-admin/includes/image.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; $title = $_POST['title']; $content = $_POST['content']; # Set Post $new_post = array( 'post_title' =&gt; $title, 'post_content' =&gt; $content, 'post_status' =&gt; 'pending', 'post_type' =&gt; 'post', ); $post_id = wp_insert_post($new_post); # Set Thumbnail $args = array( 'post_type' =&gt; 'attachment', 'posts_per_page' =&gt; -1, 'post_status' =&gt; 'pending', 'post_parent' =&gt; $post_id ); $attachments = get_posts($args); foreach($attachments as $attachment){ $attachment_id = media_handle_upload('thumbnail', $attachment-&gt;ID); } if (!is_wp_error($attachment_id)) { set_post_thumbnail($post_id, $attachment_id); header("Location: " . $_SERVER['HTTP_REFERER'] . "/?files=uploaded"); } } ?&gt; </code></pre> <p>It creates post ok. But it not sets any thumbnail. I don't know where i am wrong.</p>
[ { "answer_id": 294392, "author": "Stefano Tombolini", "author_id": 96268, "author_profile": "https://wordpress.stackexchange.com/users/96268", "pm_score": 0, "selected": false, "text": "<p>There seem to be some unnecessary code. Try the following one:</p>\n\n<pre><code>$title = $_POST['title'];\n$content = $_POST['content'];\n\n# Set Post\n\n $new_post = array(\n 'post_title' =&gt; $title,\n 'post_content' =&gt; $content,\n 'post_status' =&gt; 'pending',\n 'post_type' =&gt; 'post',\n );\n\n $post_id = wp_insert_post($new_post);\n\n # Set Thumbnail\n\n require_once(ABSPATH . \"wp-admin\" . '/includes/image.php');\n require_once(ABSPATH . \"wp-admin\" . '/includes/file.php');\n require_once(ABSPATH . \"wp-admin\" . '/includes/media.php');\n\n$attachment_id = media_handle_upload('thumbnail', $post_id);\n\nif (!is_wp_error($attachment_id)) { \n set_post_thumbnail($post_id, $attachment_id);\n header(\"Location: \" . $_SERVER['HTTP_REFERER'] . \"/?files=uploaded\");\n }\n</code></pre>\n\n<p>More info (see nonces for security too): <a href=\"https://codex.wordpress.org/Function_Reference/media_handle_upload\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/media_handle_upload</a></p>\n" }, { "answer_id": 331829, "author": "F. Gálvez", "author_id": 60487, "author_profile": "https://wordpress.stackexchange.com/users/60487", "pm_score": 1, "selected": true, "text": "<p>In form, you need the code enctype=\"multipart/form-data\" </p>\n\n<pre><code>&lt;form method=\"post\" action=\"\" enctype=\"multipart/form-data\"&gt;\n</code></pre>\n" }, { "answer_id": 361617, "author": "Syborg", "author_id": 98622, "author_profile": "https://wordpress.stackexchange.com/users/98622", "pm_score": 1, "selected": false, "text": "<p>You can use the exemple provided by the wp_insert_attachment() function <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_attachment/#comment-948\" rel=\"nofollow noreferrer\">codex page</a> and the set_post_thumbnail() <a href=\"https://developer.wordpress.org/reference/functions/set_post_thumbnail/#comment-2259\" rel=\"nofollow noreferrer\">too</a> :</p>\n\n<pre><code>$file = $_FILES['thumbnail']['tmp_name'];\n\n/*\n * $filename is the path to your uploaded file (for example as set in the $_FILE posted file array)\n * $file is the name of the file\n * first we need to upload the file into the wp upload folder.\n */\n$upload_file = wp_upload_bits( $filename, null, @file_get_contents( $file ) );\nif ( ! $upload_file['error'] ) { \n // Check the type of file. We'll use this as the 'post_mime_type'.\n $filetype = wp_check_filetype( $filename, null );\n\n // Get the path to the upload directory.\n $wp_upload_dir = wp_upload_dir();\n\n // Prepare an array of post data for the attachment.\n $attachment = array( \n 'post_mime_type' => $filetype['type'],\n 'post_title' => preg_replace( '/\\.[^.]+$/', '', $filename ),\n 'post_content' => '',\n 'post_status' => 'inherit',\n 'post_parent' => $post_id\n );\n\n // Insert the attachment.\n $attach_id = wp_insert_attachment( $attachment, $upload_file['file'], $post_id );\n\n if ( ! is_wp_error( $attachment_id ) ) { \n // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.\n require_once( ABSPATH . 'wp-admin/includes/image.php' );\n\n // Generate the metadata for the attachment, and update the database record.\n $attach_data = wp_generate_attachment_metadata( $attach_id, $upload_file['file'] );\n wp_update_attachment_metadata( $attach_id, $attach_data );\n\n set_post_thumbnail( $post_id, $attach_id );\n }\n}\n</code></pre>\n" } ]
2018/02/16
[ "https://wordpress.stackexchange.com/questions/294352", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133897/" ]
I am trying post submit on front end. All works without thumbnail uploading and setting. Here is my html form. ``` <form method="post" action=""> <input type="text" name="title"> <textarea name="content"></textarea> <input type="file" name="thumbnail"> <input type="submit" name="submit"> </form> ``` And here is my php code. ``` <?php if (isset($_POST['submit'])) { global $wpdb; require_once ABSPATH . 'wp-admin/includes/image.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; $title = $_POST['title']; $content = $_POST['content']; # Set Post $new_post = array( 'post_title' => $title, 'post_content' => $content, 'post_status' => 'pending', 'post_type' => 'post', ); $post_id = wp_insert_post($new_post); # Set Thumbnail $args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => 'pending', 'post_parent' => $post_id ); $attachments = get_posts($args); foreach($attachments as $attachment){ $attachment_id = media_handle_upload('thumbnail', $attachment->ID); } if (!is_wp_error($attachment_id)) { set_post_thumbnail($post_id, $attachment_id); header("Location: " . $_SERVER['HTTP_REFERER'] . "/?files=uploaded"); } } ?> ``` It creates post ok. But it not sets any thumbnail. I don't know where i am wrong.
In form, you need the code enctype="multipart/form-data" ``` <form method="post" action="" enctype="multipart/form-data"> ```
294,356
<p>I want that email reply should be received at multiple email address. But it is not working for me. I have tried different ways but none of these working for me. I am trying this header but it is only replying to the last email address.</p> <pre><code>$to = "[email protected]"; $subject = "my email subject"; $message = "my email message"; $headers = array(); $headers []= "MIME-Version: 1.0\r\n"; $headers []= "Content-Type: text/html; charset=UTF-8\r\n"; $headers []= "Reply-To: &lt;" . $EmailAddress1 . "&gt; &lt;" . $EmailAddressss2 . "&gt;" . "\r\n" ; wp_mail($to, $subject, $message, $headers); </code></pre> <p>I have tried without braces as well but this one is also not working</p> <pre><code>$headers []= "Reply-To: [email protected],[email protected]\r\n"; </code></pre> <p>I do not have much idea about this so little guidance about this will be much appreciated. Thank you!</p>
[ { "answer_id": 294357, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 4, "selected": true, "text": "<p><strong>Unfortunately this is not widely supported</strong>, not because WordPress does not support it, but because most email clients do not support it, so it cannot be relied upon.</p>\n<p>Instead, consider using a mailing list and use the mailing lists address as the reply to field</p>\n" }, { "answer_id": 349715, "author": "Derek Snider", "author_id": 176225, "author_profile": "https://wordpress.stackexchange.com/users/176225", "pm_score": 1, "selected": false, "text": "<p>Actually, RFC 5322 (from 2008) allows for this:</p>\n<p>RFC 5322 section-3.6.2: ( <a href=\"https://www.rfc-editor.org/rfc/rfc5322#section-3.6.2\" rel=\"nofollow noreferrer\">https://www.rfc-editor.org/rfc/rfc5322#section-3.6.2</a> )\n'In either case, an optional reply-to field MAY also be included, which\ncontains the field name &quot;Reply-To&quot; and a comma-separated list of one or\nmore addresses.'</p>\n<p>And if you think this is new, even RFC 822 (from 1982) says:\n'If the &quot;Reply-To&quot; field exists, then the reply should go to the addresses indicated in that field and not to the address(es) indicated in the &quot;From&quot; field.'</p>\n<p>So Reply-To DOES allow for multiple addresses. It's just that some clients unfortunately do not adhere to the RFC... tsk tsk tsk.</p>\n<p>You can only have one Reply-To header line, but that line can have unlimited addresses.</p>\n" }, { "answer_id": 395557, "author": "Steve Komaromi", "author_id": 212421, "author_profile": "https://wordpress.stackexchange.com/users/212421", "pm_score": 0, "selected": false, "text": "<p>Well that is true however many of my tests on Outlook and Yahoo indicates that all email addresses are dropped after the comma. Only the first email address is being used to populate the &quot;To&quot; field.</p>\n" } ]
2018/02/17
[ "https://wordpress.stackexchange.com/questions/294356", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120693/" ]
I want that email reply should be received at multiple email address. But it is not working for me. I have tried different ways but none of these working for me. I am trying this header but it is only replying to the last email address. ``` $to = "[email protected]"; $subject = "my email subject"; $message = "my email message"; $headers = array(); $headers []= "MIME-Version: 1.0\r\n"; $headers []= "Content-Type: text/html; charset=UTF-8\r\n"; $headers []= "Reply-To: <" . $EmailAddress1 . "> <" . $EmailAddressss2 . ">" . "\r\n" ; wp_mail($to, $subject, $message, $headers); ``` I have tried without braces as well but this one is also not working ``` $headers []= "Reply-To: [email protected],[email protected]\r\n"; ``` I do not have much idea about this so little guidance about this will be much appreciated. Thank you!
**Unfortunately this is not widely supported**, not because WordPress does not support it, but because most email clients do not support it, so it cannot be relied upon. Instead, consider using a mailing list and use the mailing lists address as the reply to field
294,394
<p>I'm trying to add a custom data attribute to the <code>&lt;a&gt;</code> element. What I'm trying to do is integrate the navigation effect in this <a href="https://codepen.io/littlesnippets/pen/pjmXvP" rel="nofollow noreferrer">CodePen</a></p> <p>I can do all the CSS but I need to add the HTML part such as below:</p> <pre><code> &lt;ul class="snip1226"&gt; &lt;li class="current"&gt;&lt;a href="#" data-hover="Home"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" data-hover="About Us"&gt;About Us&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" data-hover="Blog"&gt;Blog&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" data-hover="Services"&gt;Services&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" data-hover="Products"&gt;Products&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" data-hover="Contact"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>How and where would I add this into WordPress? What would I need to edit to add this HTML functionally?</p> <p>Thanks,</p> <p>Harvey</p>
[ { "answer_id": 294398, "author": "Den Isahac", "author_id": 113233, "author_profile": "https://wordpress.stackexchange.com/users/113233", "pm_score": 1, "selected": false, "text": "<p>If you want to add a custom <code>data</code> attributes to the menu that's generated by <a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"nofollow noreferrer\"><code>wp_nav_menu</code></a> function. You can use the <a href=\"https://developer.wordpress.org/reference/hooks/nav_menu_link_attributes/\" rel=\"nofollow noreferrer\"><code>nav_menu_link_attributes</code></a> filter to add the desired attributes to the <code>&lt;a&gt;</code> elements.</p>\n\n<pre><code>function add_menu_atts( $atts, $item, $args ) {\n $atts['data-hover'] = $atts['title']; // add data-hover attribute\n\n return $atts;\n}\nadd_filter( 'nav_menu_link_attributes', 'add_menu_atts', 10, 3 );\n</code></pre>\n" }, { "answer_id": 353098, "author": "user1551496", "author_id": 111109, "author_profile": "https://wordpress.stackexchange.com/users/111109", "pm_score": 0, "selected": false, "text": "<p>You can also try:</p>\n\n<pre><code>/*\n * Add filter attribute \n */\n\nadd_filter( 'walker_nav_menu_start_el', 'modify_walker_data_attr', 10, 4);\n\nfunction modify_walker_data_attr( $item_output, $item, $depth, $args )\n{\n\n // I use ACF for adding field to a menu item\n // https://www.advancedcustomfields.com/resources/adding-fields-menu-items/\n $data_hover = get_field('data-hover', $item);\n\n $old = '&lt;a';\n $new = '&lt;a data-hover=\"'.$data_hover.'\" ';\n\n $item_output = str_replace($old, $new, $item_output);\n\n return $item_output;\n}\n</code></pre>\n" } ]
2018/02/17
[ "https://wordpress.stackexchange.com/questions/294394", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125303/" ]
I'm trying to add a custom data attribute to the `<a>` element. What I'm trying to do is integrate the navigation effect in this [CodePen](https://codepen.io/littlesnippets/pen/pjmXvP) I can do all the CSS but I need to add the HTML part such as below: ``` <ul class="snip1226"> <li class="current"><a href="#" data-hover="Home">Home</a></li> <li><a href="#" data-hover="About Us">About Us</a></li> <li><a href="#" data-hover="Blog">Blog</a></li> <li><a href="#" data-hover="Services">Services</a></li> <li><a href="#" data-hover="Products">Products</a></li> <li><a href="#" data-hover="Contact">Contact</a></li> </ul> ``` How and where would I add this into WordPress? What would I need to edit to add this HTML functionally? Thanks, Harvey
If you want to add a custom `data` attributes to the menu that's generated by [`wp_nav_menu`](https://developer.wordpress.org/reference/functions/wp_nav_menu/) function. You can use the [`nav_menu_link_attributes`](https://developer.wordpress.org/reference/hooks/nav_menu_link_attributes/) filter to add the desired attributes to the `<a>` elements. ``` function add_menu_atts( $atts, $item, $args ) { $atts['data-hover'] = $atts['title']; // add data-hover attribute return $atts; } add_filter( 'nav_menu_link_attributes', 'add_menu_atts', 10, 3 ); ```
294,413
<p>Bonsouir, I'm trying to redirect to checkout when a user add to cart a product just from the single product page, to be very specific from this page where everyone can see just the simple product</p> <p><a href="https://i.stack.imgur.com/u6U8U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u6U8U.png" alt="enter image description here"></a></p> <p>Now, everythings works just fine when I add this code to functions.php</p> <pre><code>function my_custom_add_to_cart_redirect( $url ) { $url = wc_get_checkout_url(); return $url; } add_filter( 'woocommerce_add_to_cart_redirect','my_custom_add_to_cart_redirect'); </code></pre> <p>But when i modify the code adding the condition to discriminate between the pages that are not the single product page with this code it doesnt work</p> <pre><code>function my_custom_add_to_cart_redirect( $url ) { if ( is_product() ){ $url = wc_get_checkout_url(); return $url; } } add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect' ); </code></pre> <p>I put inside the condition an <code>echo "it works"</code> and prints quite well but the redirect is not working.</p> <p>Where do you think is the problem, this should works, is just an easy condition but dont work for me, Im using Avada Theme and Woocommerce updated</p> <p><strong>EDIT</strong> : It looks like when I add to cart, the links is generated as </p> <pre><code>[www.domain.com]/product/[name-of-product]/?add-to-cart=[PRODUCTID] </code></pre> <p>The path </p> <pre><code>[www.domain.com]/product/[name-of-product]/ </code></pre> <p>IS considered for woocommmerce as product but the other one that includes <code>?add-to-cart=[PRODUCTID]</code> is not considered as product but it should be because it still is a product, is just sending a variable via GET</p> <p>Do you know how to make recognize it as a product page ?</p>
[ { "answer_id": 294470, "author": "Aadil P.", "author_id": 49322, "author_profile": "https://wordpress.stackexchange.com/users/49322", "pm_score": 0, "selected": false, "text": "<p>The function is_product() and/or is_single() can only identify the page after wp_query() is ready.\nApparently, at the time your code is running, the said wp_query() has nothing and can not identify whether it is a single page or a category page etc. Thus, in your code the is_product() function is returning (bool) false.</p>\n\n<p>On reproducing your code, I printed the wp_query from functions file and it yielded the result below.</p>\n\n<p>What you want to achieve, might be possible, if you add your action after wp_query() is ready, in that case the second function to change redirect page <em>might</em> work.</p>\n\n<blockquote>\n <p>WP_Query Object (\n [query] => \n [query_vars] => Array\n (\n )</p>\n\n<pre><code>[tax_query] =&gt; \n[meta_query] =&gt; \n[date_query] =&gt; \n[queried_object] =&gt; \n[queried_object_id] =&gt; \n[request] =&gt; \n[posts] =&gt; \n[post_count] =&gt; 0\n[current_post] =&gt; -1\n[in_the_loop] =&gt; \n[post] =&gt; \n[comments] =&gt; \n[comment_count] =&gt; 0\n[current_comment] =&gt; -1\n[comment] =&gt; \n[found_posts] =&gt; 0\n[max_num_pages] =&gt; 0\n[max_num_comment_pages] =&gt; 0\n[is_single] =&gt; \n[is_preview] =&gt; \n[is_page] =&gt; \n[is_archive] =&gt; \n[is_date] =&gt; \n[is_year] =&gt; \n[is_month] =&gt; \n[is_day] =&gt; \n[is_time] =&gt; \n[is_author] =&gt; \n[is_category] =&gt; \n[is_tag] =&gt; \n[is_tax] =&gt; \n[is_search] =&gt; \n[is_feed] =&gt; \n[is_comment_feed] =&gt; \n[is_trackback] =&gt; \n[is_home] =&gt; \n[is_404] =&gt; \n[is_embed] =&gt; \n[is_paged] =&gt; \n[is_admin] =&gt; \n[is_attachment] =&gt; \n[is_singular] =&gt; \n[is_robots] =&gt; \n[is_posts_page] =&gt; \n[is_post_type_archive] =&gt; \n[query_vars_hash:WP_Query:private] =&gt; \n[query_vars_changed:WP_Query:private] =&gt; 1\n[thumbnails_cached] =&gt; \n[stopwords:WP_Query:private] =&gt; \n[compat_fields:WP_Query:private] =&gt; Array\n (\n [0] =&gt; query_vars_hash\n [1] =&gt; query_vars_changed\n )\n\n[compat_methods:WP_Query:private] =&gt; Array\n (\n [0] =&gt; init_query_flags\n [1] =&gt; parse_tax_query\n )\n</code></pre>\n \n <p>) IS PRODUCT ? bool(false)</p>\n</blockquote>\n" }, { "answer_id": 295497, "author": "Johanna Ferreira", "author_id": 130802, "author_profile": "https://wordpress.stackexchange.com/users/130802", "pm_score": 2, "selected": true, "text": "<p>Well, what it works for me in this case was this code</p>\n\n<pre><code>add_filter( 'woocommerce_add_to_cart_redirect', 'redirect_add_to_cart' );\n\nfunction redirect_add_to_cart() { \n if ( isset( $_POST['add-to-cart'] ) ) {\n $url = wc_get_checkout_url();\n return $url;\n } \n}\n</code></pre>\n\n<p>It redirects if it is a product but if you are in the shop page it wont redirect, of course if you want to redirect in another page but in single product page the code should be <code>if ( !isset( $_POST['add-to-cart'] ) ) {</code></p>\n\n<p>I hope my question and answer helps somebody who visits this post</p>\n" }, { "answer_id": 319257, "author": "Misha Rudrastyh", "author_id": 85985, "author_profile": "https://wordpress.stackexchange.com/users/85985", "pm_score": 0, "selected": false, "text": "<p>I just want to add to this question, that when you perform the checkout redirect, you probably want to change add to cart button text, it is possible with <code>woocommerce_product_add_to_cart_text</code> for product archives, and with <code>woocommerce_product_single_add_to_cart_text</code> for single product pages.</p>\n\n<p>The next issue is the \"The {product name} has been added to your cart\" notice. Probably you want to hide it too, because it is shown on checkout page. It is possible too with <code>wc_add_to_cart_message_html</code> hook.</p>\n\n<p>Code example you can find in <a href=\"https://rudrastyh.com/woocommerce/redirect-to-checkout-skip-cart.html\" rel=\"nofollow noreferrer\">this</a> article.</p>\n" } ]
2018/02/17
[ "https://wordpress.stackexchange.com/questions/294413", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130802/" ]
Bonsouir, I'm trying to redirect to checkout when a user add to cart a product just from the single product page, to be very specific from this page where everyone can see just the simple product [![enter image description here](https://i.stack.imgur.com/u6U8U.png)](https://i.stack.imgur.com/u6U8U.png) Now, everythings works just fine when I add this code to functions.php ``` function my_custom_add_to_cart_redirect( $url ) { $url = wc_get_checkout_url(); return $url; } add_filter( 'woocommerce_add_to_cart_redirect','my_custom_add_to_cart_redirect'); ``` But when i modify the code adding the condition to discriminate between the pages that are not the single product page with this code it doesnt work ``` function my_custom_add_to_cart_redirect( $url ) { if ( is_product() ){ $url = wc_get_checkout_url(); return $url; } } add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect' ); ``` I put inside the condition an `echo "it works"` and prints quite well but the redirect is not working. Where do you think is the problem, this should works, is just an easy condition but dont work for me, Im using Avada Theme and Woocommerce updated **EDIT** : It looks like when I add to cart, the links is generated as ``` [www.domain.com]/product/[name-of-product]/?add-to-cart=[PRODUCTID] ``` The path ``` [www.domain.com]/product/[name-of-product]/ ``` IS considered for woocommmerce as product but the other one that includes `?add-to-cart=[PRODUCTID]` is not considered as product but it should be because it still is a product, is just sending a variable via GET Do you know how to make recognize it as a product page ?
Well, what it works for me in this case was this code ``` add_filter( 'woocommerce_add_to_cart_redirect', 'redirect_add_to_cart' ); function redirect_add_to_cart() { if ( isset( $_POST['add-to-cart'] ) ) { $url = wc_get_checkout_url(); return $url; } } ``` It redirects if it is a product but if you are in the shop page it wont redirect, of course if you want to redirect in another page but in single product page the code should be `if ( !isset( $_POST['add-to-cart'] ) ) {` I hope my question and answer helps somebody who visits this post
294,414
<p>I have two number and an operator in three variables. For example $number1, $number2 and $operator. $operator contains only an operator from an array of (+, -, *, /). Now my question is how can I calculate mathematical operation with these three variables? For example $number1 ($operator) $number2 = ?</p>
[ { "answer_id": 294415, "author": "Beee", "author_id": 103402, "author_profile": "https://wordpress.stackexchange.com/users/103402", "pm_score": -1, "selected": false, "text": "<p>I think it can be done very simple, if I understand it correctly.</p>\n\n<pre><code>$operators = array( '+', '-', '*', '/' );\n$key = rand( 0, 3 );\n$result = $number1 . $operator[$key] . $number2;\n</code></pre>\n\n<p>I think the <code>. ' ' .</code> can also be replaced by just a <code>.</code> but I like 'spacious/clear' code.</p>\n" }, { "answer_id": 294416, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 1, "selected": true, "text": "<p>Recommend you just stick to <code>*</code> and <code>+</code>, not expect people to deal with decimals and negative numbers. It is best to keep it simple as possible and not attempt to <code>eval</code> the string as an expression which is not good practice:</p>\n\n<pre><code>$operators = array('+', '*');\n$operator = rand(0, 1);\n$display = $number1.' '.$operators[$operator].' '.$number2;\nif ($operators[$operator] == \"*\") {$result = $number1 * $number2;}\nelseif ($operators[$operator] == \"+\") {$result = $number1 + $number2;}\n</code></pre>\n\n<p>Of course there are other ways to calculate without <code>eval</code>, <a href=\"https://stackoverflow.com/a/16071456/5240159\">such as in this answer</a>, but probably not worth it unless you are doing something more complex.</p>\n" } ]
2018/02/18
[ "https://wordpress.stackexchange.com/questions/294414", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136361/" ]
I have two number and an operator in three variables. For example $number1, $number2 and $operator. $operator contains only an operator from an array of (+, -, \*, /). Now my question is how can I calculate mathematical operation with these three variables? For example $number1 ($operator) $number2 = ?
Recommend you just stick to `*` and `+`, not expect people to deal with decimals and negative numbers. It is best to keep it simple as possible and not attempt to `eval` the string as an expression which is not good practice: ``` $operators = array('+', '*'); $operator = rand(0, 1); $display = $number1.' '.$operators[$operator].' '.$number2; if ($operators[$operator] == "*") {$result = $number1 * $number2;} elseif ($operators[$operator] == "+") {$result = $number1 + $number2;} ``` Of course there are other ways to calculate without `eval`, [such as in this answer](https://stackoverflow.com/a/16071456/5240159), but probably not worth it unless you are doing something more complex.
294,419
<p>This is a doozy, you’ll like it. Since about a week ago, when I edit a post, if that post contains a hyperlink (eg <code>&lt;a href="..."&gt;...&lt;/a&gt;</code>) when I update it, I’m sent to the 404 “Page not Found” page, and the post is NOT saved. Here’s a video: <a href="https://drive.google.com/file/d/1OQZ9k5f_jxbxsT4SEyD-pH28FSIMoQlT/view" rel="nofollow noreferrer">https://drive.google.com/file/d/1OQZ9k5f_jxbxsT4SEyD-pH28FSIMoQlT/view</a>.</p> <p>I added some debug code to wp-admin/post.php to see if it’s getting called when the POST request is sent, and it isn’t. The request is somehow going to index.php, and there’s no URL rewrite for that, so it becomes a 404.</p> <p>I was suspicious that the plugin “Auto Affiliate Links” was the culprit (<a href="https://wordpress.org/plugins/wp-auto-affiliate-links/" rel="nofollow noreferrer">https://wordpress.org/plugins/wp-auto-affiliate-links/</a>), because it changes hyperlinks to be affiliate links, and was having some error. But the error still happens when after I’ve deactivated the plugin.</p> <p>In fact, I temporarily switched the site to a use a fresh DB (all default settings), with default (twenty seventeen) theme, NO plugins active, and I still get the same problem. However, when I copied the directory containing WordPress’ files to a local copy (running VVV), I did not get the issue.</p> <p>So it seems very unlikely that it’s a plugin causing the issue, because the issue persists with all plugins deactivated, and even on a fresh DB (so they couldn’t have changed something in the database). The only way a plugin could be the culprit would be if they changed WP core FILES, right? But if that were the case, I would have expected to reproduce the issue when using those same files on my local VVV site. Right?</p> <p>I don’t think it’s a WP configuration issue because I get the same issue on a fresh install of WP.</p> <p>I was suspcious that maybe it was a .htaccess issue, but here’s my vanilla htaccess file:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>Looks pretty regular, right?</p> <p>The last possibility, I think, is the hosting company, uniserve (<a href="https://www.uniserve.com/" rel="nofollow noreferrer">https://www.uniserve.com/</a>) has something running on the webserver that’s intercepting the request for /wp-admin/post.php and instead sending it to /index.php, but only when the post content has a hyperlink in it. Maybe it’s an attempt at blocking some spammers from creating posts with backlinks to their site or something.</p>
[ { "answer_id": 294415, "author": "Beee", "author_id": 103402, "author_profile": "https://wordpress.stackexchange.com/users/103402", "pm_score": -1, "selected": false, "text": "<p>I think it can be done very simple, if I understand it correctly.</p>\n\n<pre><code>$operators = array( '+', '-', '*', '/' );\n$key = rand( 0, 3 );\n$result = $number1 . $operator[$key] . $number2;\n</code></pre>\n\n<p>I think the <code>. ' ' .</code> can also be replaced by just a <code>.</code> but I like 'spacious/clear' code.</p>\n" }, { "answer_id": 294416, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 1, "selected": true, "text": "<p>Recommend you just stick to <code>*</code> and <code>+</code>, not expect people to deal with decimals and negative numbers. It is best to keep it simple as possible and not attempt to <code>eval</code> the string as an expression which is not good practice:</p>\n\n<pre><code>$operators = array('+', '*');\n$operator = rand(0, 1);\n$display = $number1.' '.$operators[$operator].' '.$number2;\nif ($operators[$operator] == \"*\") {$result = $number1 * $number2;}\nelseif ($operators[$operator] == \"+\") {$result = $number1 + $number2;}\n</code></pre>\n\n<p>Of course there are other ways to calculate without <code>eval</code>, <a href=\"https://stackoverflow.com/a/16071456/5240159\">such as in this answer</a>, but probably not worth it unless you are doing something more complex.</p>\n" } ]
2018/02/18
[ "https://wordpress.stackexchange.com/questions/294419", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52760/" ]
This is a doozy, you’ll like it. Since about a week ago, when I edit a post, if that post contains a hyperlink (eg `<a href="...">...</a>`) when I update it, I’m sent to the 404 “Page not Found” page, and the post is NOT saved. Here’s a video: <https://drive.google.com/file/d/1OQZ9k5f_jxbxsT4SEyD-pH28FSIMoQlT/view>. I added some debug code to wp-admin/post.php to see if it’s getting called when the POST request is sent, and it isn’t. The request is somehow going to index.php, and there’s no URL rewrite for that, so it becomes a 404. I was suspicious that the plugin “Auto Affiliate Links” was the culprit (<https://wordpress.org/plugins/wp-auto-affiliate-links/>), because it changes hyperlinks to be affiliate links, and was having some error. But the error still happens when after I’ve deactivated the plugin. In fact, I temporarily switched the site to a use a fresh DB (all default settings), with default (twenty seventeen) theme, NO plugins active, and I still get the same problem. However, when I copied the directory containing WordPress’ files to a local copy (running VVV), I did not get the issue. So it seems very unlikely that it’s a plugin causing the issue, because the issue persists with all plugins deactivated, and even on a fresh DB (so they couldn’t have changed something in the database). The only way a plugin could be the culprit would be if they changed WP core FILES, right? But if that were the case, I would have expected to reproduce the issue when using those same files on my local VVV site. Right? I don’t think it’s a WP configuration issue because I get the same issue on a fresh install of WP. I was suspcious that maybe it was a .htaccess issue, but here’s my vanilla htaccess file: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` Looks pretty regular, right? The last possibility, I think, is the hosting company, uniserve (<https://www.uniserve.com/>) has something running on the webserver that’s intercepting the request for /wp-admin/post.php and instead sending it to /index.php, but only when the post content has a hyperlink in it. Maybe it’s an attempt at blocking some spammers from creating posts with backlinks to their site or something.
Recommend you just stick to `*` and `+`, not expect people to deal with decimals and negative numbers. It is best to keep it simple as possible and not attempt to `eval` the string as an expression which is not good practice: ``` $operators = array('+', '*'); $operator = rand(0, 1); $display = $number1.' '.$operators[$operator].' '.$number2; if ($operators[$operator] == "*") {$result = $number1 * $number2;} elseif ($operators[$operator] == "+") {$result = $number1 + $number2;} ``` Of course there are other ways to calculate without `eval`, [such as in this answer](https://stackoverflow.com/a/16071456/5240159), but probably not worth it unless you are doing something more complex.
294,464
<p>This is my Code</p> <pre><code>if($totalPage &gt; 1){ $customPagHTML = paginate_links( array( 'base' =&gt; add_query_arg( 'cp', '%#%' ), 'format' =&gt; '', 'prev_text' =&gt; __('Back', '&amp;laquo;'), 'next_text' =&gt; __('Next', '&amp;raquo;'), 'total' =&gt; $totalPage, 'current' =&gt; $page, 'type' =&gt; '' ) ); } echo $customPagHTML; </code></pre> <p>Link showing like that:- site.com/page/?cp=2</p> <p>But I want to show it like : <strong>site.com/page/cp/2</strong> or <strong>site.com/page/2</strong></p> <p>Note: Getting result from custom db table </p> <pre><code>$query = "SELECT * FROM custom_table WHERE custom_table.id = '$id'"; </code></pre>
[ { "answer_id": 294415, "author": "Beee", "author_id": 103402, "author_profile": "https://wordpress.stackexchange.com/users/103402", "pm_score": -1, "selected": false, "text": "<p>I think it can be done very simple, if I understand it correctly.</p>\n\n<pre><code>$operators = array( '+', '-', '*', '/' );\n$key = rand( 0, 3 );\n$result = $number1 . $operator[$key] . $number2;\n</code></pre>\n\n<p>I think the <code>. ' ' .</code> can also be replaced by just a <code>.</code> but I like 'spacious/clear' code.</p>\n" }, { "answer_id": 294416, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 1, "selected": true, "text": "<p>Recommend you just stick to <code>*</code> and <code>+</code>, not expect people to deal with decimals and negative numbers. It is best to keep it simple as possible and not attempt to <code>eval</code> the string as an expression which is not good practice:</p>\n\n<pre><code>$operators = array('+', '*');\n$operator = rand(0, 1);\n$display = $number1.' '.$operators[$operator].' '.$number2;\nif ($operators[$operator] == \"*\") {$result = $number1 * $number2;}\nelseif ($operators[$operator] == \"+\") {$result = $number1 + $number2;}\n</code></pre>\n\n<p>Of course there are other ways to calculate without <code>eval</code>, <a href=\"https://stackoverflow.com/a/16071456/5240159\">such as in this answer</a>, but probably not worth it unless you are doing something more complex.</p>\n" } ]
2018/02/19
[ "https://wordpress.stackexchange.com/questions/294464", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136190/" ]
This is my Code ``` if($totalPage > 1){ $customPagHTML = paginate_links( array( 'base' => add_query_arg( 'cp', '%#%' ), 'format' => '', 'prev_text' => __('Back', '&laquo;'), 'next_text' => __('Next', '&raquo;'), 'total' => $totalPage, 'current' => $page, 'type' => '' ) ); } echo $customPagHTML; ``` Link showing like that:- site.com/page/?cp=2 But I want to show it like : **site.com/page/cp/2** or **site.com/page/2** Note: Getting result from custom db table ``` $query = "SELECT * FROM custom_table WHERE custom_table.id = '$id'"; ```
Recommend you just stick to `*` and `+`, not expect people to deal with decimals and negative numbers. It is best to keep it simple as possible and not attempt to `eval` the string as an expression which is not good practice: ``` $operators = array('+', '*'); $operator = rand(0, 1); $display = $number1.' '.$operators[$operator].' '.$number2; if ($operators[$operator] == "*") {$result = $number1 * $number2;} elseif ($operators[$operator] == "+") {$result = $number1 + $number2;} ``` Of course there are other ways to calculate without `eval`, [such as in this answer](https://stackoverflow.com/a/16071456/5240159), but probably not worth it unless you are doing something more complex.
294,480
<p>I am modifying a WordPress theme, but the problem is every time I edit my CSS file via FileZilla and upload it to the server, the CSS file doesn't get updated immediately after browser refresh and it's very frustrating.</p> <p>I get the idea that the CSS <code>ver</code> tag is helping browser not to cache old CSS files, but for the temporary purpose, I would like to disable it.</p> <p>Can you guys give me a hint, how the code of <code>style.css?ver=1.0.0</code> tag command might look like? So that I can reverse engineer it and modify it my self or remove it completely.</p>
[ { "answer_id": 294483, "author": "obiPlabon", "author_id": 135737, "author_profile": "https://wordpress.stackexchange.com/users/135737", "pm_score": 2, "selected": false, "text": "<p>You're facing browser caching problem and it's not because of <code>ver</code>. Every time you update your CSS or JS files you should hard refresh your browser using <code>Ctrl + Shift + R</code> or you can change the <code>ver</code> value. If the default <code>ver</code> is <code>ver=1.0.0</code> then update the <code>ver</code> to <code>ver=1.0.1</code>. The point is, change the <code>ver</code> value to something you didn't set before.</p>\n\n<p>Most of the time the <code>ver</code> value comes from theme version. So you can try updating the <code>Version</code> parameter in <code>style.css</code> or find a theme version constant and update the value if there's any.</p>\n\n<p>And if you still need to remove <code>ver</code> then add the following code in your <code>functions.php</code> and <code>ver</code> will be removed automatically -</p>\n\n<pre><code>add_filter( 'style_loader_src', function( $src, $handle ) {\n // If you know the handle\n // if ( 'your-css-handle' === $handle ) {\n // return remove_query_arg( 'ver', $src );\n // }\n // return $src;\n return remove_query_arg( 'ver', $src );\n}, 10, 2 );\n</code></pre>\n" }, { "answer_id": 294485, "author": "Dilip Gupta", "author_id": 110899, "author_profile": "https://wordpress.stackexchange.com/users/110899", "pm_score": 0, "selected": false, "text": "<p>Have you tried finding the solution enough, there is already many thread for your solution.\n<a href=\"https://wordpress.stackexchange.com/questions/233543/how-to-remove-the-wordpress-version-from-some-css-js-files\">How to remove version from css</a></p>\n\n<p>To simplify check this.</p>\n\n<pre><code>add_filter( 'style_loader_src', 'sdt_remove_ver_css_js', 9999, 2 );\n\nfunction sdt_remove_ver_css_js( $src, $handle ) \n{\n$handles_with_version = [ 'style' ]; // &lt;-- Adjust to your needs!\n\nif ( strpos( $src, 'ver=' ) &amp;&amp; ! in_array( $handle, $handles_with_version, true ) )\n $src = remove_query_arg( 'ver', $src );\n\nreturn $src;\n}\n</code></pre>\n" } ]
2018/02/19
[ "https://wordpress.stackexchange.com/questions/294480", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125422/" ]
I am modifying a WordPress theme, but the problem is every time I edit my CSS file via FileZilla and upload it to the server, the CSS file doesn't get updated immediately after browser refresh and it's very frustrating. I get the idea that the CSS `ver` tag is helping browser not to cache old CSS files, but for the temporary purpose, I would like to disable it. Can you guys give me a hint, how the code of `style.css?ver=1.0.0` tag command might look like? So that I can reverse engineer it and modify it my self or remove it completely.
You're facing browser caching problem and it's not because of `ver`. Every time you update your CSS or JS files you should hard refresh your browser using `Ctrl + Shift + R` or you can change the `ver` value. If the default `ver` is `ver=1.0.0` then update the `ver` to `ver=1.0.1`. The point is, change the `ver` value to something you didn't set before. Most of the time the `ver` value comes from theme version. So you can try updating the `Version` parameter in `style.css` or find a theme version constant and update the value if there's any. And if you still need to remove `ver` then add the following code in your `functions.php` and `ver` will be removed automatically - ``` add_filter( 'style_loader_src', function( $src, $handle ) { // If you know the handle // if ( 'your-css-handle' === $handle ) { // return remove_query_arg( 'ver', $src ); // } // return $src; return remove_query_arg( 'ver', $src ); }, 10, 2 ); ```
294,568
<p>I've read a lot of questions about this topic. None of them solve my issue.</p> <p><strong>Poblem</strong>: pagination is shown at page 1 but page 2 returns 404.</p> <p>The query and loop are in front-page.php:</p> <pre><code>// WP_Query arguments $args = array( 'post_type' =&gt; 'trabajo', 'posts_per_page' =&gt; '2', 'paged' =&gt; ( get_query_var('paged') ) ? get_query_var('paged') : 1, ); // The Query $trabajo_query = new WP_Query( $args ); $temp_query = $wp_query; $wp_query = NULL; $wp_query = $trabajo_query; // The Loop if ( have_posts() ) { while ( have_posts() ) { the_post(); the_title(); } } wp_reset_postdata(); the_posts_navigation(); $wp_query = NULL; $wp_query = $temp_query; // Reset </code></pre>
[ { "answer_id": 294573, "author": "aitor", "author_id": 77722, "author_profile": "https://wordpress.stackexchange.com/users/77722", "pm_score": 1, "selected": false, "text": "<p>I found here a workaround: <a href=\"https://wordpress.stackexchange.com/questions/22528/custom-post-type-pagination-404-fix\">Custom post type pagination 404 fix?</a></p>\n\n<p>Since I don't understand it, I don't mark this question as solved. Any explanation of this will be appreciated.</p>\n\n<p>I must to do two actions together:</p>\n\n<ol>\n<li>Set <code>1</code> the post limit in the admin>reading dashboard.</li>\n<li>Add this function:</li>\n</ol>\n\n<p>.</p>\n\n<pre><code>add_action( 'parse_query','changept' );\nfunction changept() {\n if( !is_admin() )\n set_query_var( 'post_type', array( 'post', 'trabajo' ) );\n return;\n}\n</code></pre>\n\n<p>It works, but I don't know what side effects will have this.</p>\n" }, { "answer_id": 294580, "author": "aitor", "author_id": 77722, "author_profile": "https://wordpress.stackexchange.com/users/77722", "pm_score": 3, "selected": true, "text": "<p>I found the final answer here: <a href=\"https://wordpress.stackexchange.com/a/217534/77722\">https://wordpress.stackexchange.com/a/217534/77722</a></p>\n\n<p>Page 2 of front page was taking pagination from main query, not from my custom query.</p>\n\n<p>I've taked these actions:</p>\n\n<p><strong>1. To change name of front-page.php to index.php</strong> in order to get the main query every time page is loaded (even when paginated)</p>\n\n<p><strong>2. To change main query with pre_get_posts</strong> in order to show posts of my CPT:</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q ) {\n if ( $q-&gt;is_home() &amp;&amp; $q-&gt;is_main_query() ) {\n $q-&gt;set( 'posts_per_page', 1 );\n $q-&gt;set( 'post_type', 'trabajo');\n }\n});\n</code></pre>\n\n<p><strong>3. Do a normal loop in the index.php:</strong></p>\n\n<pre><code>if ( have_posts() ) {\n while ( have_posts() ) {\n the_post();\n the_title();\n }\n}\nwp_reset_postdata();\nthe_posts_navigation();\n</code></pre>\n\n<p>Works perfectly!</p>\n" }, { "answer_id": 294588, "author": "Bhumi champaneria", "author_id": 102082, "author_profile": "https://wordpress.stackexchange.com/users/102082", "pm_score": -1, "selected": false, "text": "<p>Put this code in functions.php file</p>\n\n<pre><code> function pagination($pages = '', $range = 1) {\n $showitems = ($range * 3) + 1;\n\n global $paged;\n if (empty($paged))\n $paged = 1;\n\n if ($pages == '') {\n global $wp_query;\n $pages = $wp_query-&gt;max_num_pages;\n if (!$pages) {\n $pages = 1;\n }\n }\n\n if (1 != $pages) {\n echo \"&lt;div class=\\\"gallery-pagination\\\"&gt;\";\n echo '&lt;ul class=\"pagination\"&gt;';\n// if ($paged &gt; 2 &amp;&amp; $paged &gt; $range + 1 &amp;&amp; $showitems &lt; $pages)\n// echo \"&lt;a href='\" . get_pagenum_link(1) . \"'&gt;&amp;laquo; First&lt;/a&gt;\";\n if ($paged &gt; 1 &amp;&amp; $showitems &lt; $pages)\n echo \"&lt;a href='\" . get_pagenum_link($paged - 1) . \"'&gt; &lt;&lt; &lt;/a&gt;\";\n// echo '&lt;ul class=\"pagination\"&gt;';\n for ($i = 1; $i &lt;= $pages; $i++) {\n\n if (1 != $pages &amp;&amp; (!($i &gt;= $paged + $range + 1 || $i &lt;= $paged - $range - 1) || $pages &lt;= $showitems )) {\n echo ($paged == $i) ? \"&lt;li class='active'&gt;&lt;a href='javascript:void(0)'&gt;\" . $i . \"&lt;/a&gt;&lt;/li&gt;\" : \"&lt;li class='inactive'&gt;&lt;a href='\" . get_pagenum_link($i) . \"'&gt;\" . $i . \"&lt;/a&gt;&lt;/li&gt;\";\n }\n }\n\n if ($paged &lt; $pages &amp;&amp; $showitems &lt; $pages)\n echo \"&lt;a href=\\\"\" . get_pagenum_link($paged + 1) . \"\\\"&gt; &gt;&gt; &lt;/a&gt;\";\n echo '&lt;/ul&gt;';\n\n echo \"&lt;/div&gt;\\n\";\n }\n }\n</code></pre>\n\n<p>Put this code in your custom post type page where you want it.</p>\n\n<pre><code>&lt;?php\n // Get a list of categories\n $paged = ( get_query_var('paged') ) ? absint(get_query_var('paged')) : 1;\n $args = array(\n 'post_type' =&gt; 'post_gallery',\n 'posts_per_page' =&gt; 9,\n 'order_by' =&gt; 'date',\n 'order' =&gt; 'ASC',\n 'paged' =&gt; $paged,\n );\n\n $new_query = new WP_Query($args);\n// print_r($new_query);\n ?&gt;\n&lt;?php if (function_exists(\"pagination\")) { ?&gt;\n &lt;?php pagination($new_query-&gt;max_num_pages); ?&gt;\n &lt;?php } ?&gt;\n</code></pre>\n" } ]
2018/02/20
[ "https://wordpress.stackexchange.com/questions/294568", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77722/" ]
I've read a lot of questions about this topic. None of them solve my issue. **Poblem**: pagination is shown at page 1 but page 2 returns 404. The query and loop are in front-page.php: ``` // WP_Query arguments $args = array( 'post_type' => 'trabajo', 'posts_per_page' => '2', 'paged' => ( get_query_var('paged') ) ? get_query_var('paged') : 1, ); // The Query $trabajo_query = new WP_Query( $args ); $temp_query = $wp_query; $wp_query = NULL; $wp_query = $trabajo_query; // The Loop if ( have_posts() ) { while ( have_posts() ) { the_post(); the_title(); } } wp_reset_postdata(); the_posts_navigation(); $wp_query = NULL; $wp_query = $temp_query; // Reset ```
I found the final answer here: <https://wordpress.stackexchange.com/a/217534/77722> Page 2 of front page was taking pagination from main query, not from my custom query. I've taked these actions: **1. To change name of front-page.php to index.php** in order to get the main query every time page is loaded (even when paginated) **2. To change main query with pre\_get\_posts** in order to show posts of my CPT: ``` add_action( 'pre_get_posts', function ( $q ) { if ( $q->is_home() && $q->is_main_query() ) { $q->set( 'posts_per_page', 1 ); $q->set( 'post_type', 'trabajo'); } }); ``` **3. Do a normal loop in the index.php:** ``` if ( have_posts() ) { while ( have_posts() ) { the_post(); the_title(); } } wp_reset_postdata(); the_posts_navigation(); ``` Works perfectly!
294,575
<p>I recently imported large number of custom posts into wordpress. all works fine, except one taxonomy which is imported, but not show at the front end, until i click on every post "update" button. I have 810 posts and this is not a solution...</p> <p>i think it should be the way to run MYSQL command to force all post update without making any changes. Please help me with command, i searched for plugins and cannot find anything suitable</p> <p>Thank you</p>
[ { "answer_id": 294579, "author": "Clinton", "author_id": 122375, "author_profile": "https://wordpress.stackexchange.com/users/122375", "pm_score": 3, "selected": false, "text": "<p>There are 2 ways that you could do this. The first and more difficult is to write a program, the other is to do a bulk update. Why do difficult when easy way will work equally well? and especially as this is a once-off requirement</p>\n\n<p>The easy way:</p>\n\n<ol>\n<li>In the admin dashboard, select the view with all posts for your custom type</li>\n<li>Select all the posts (tick them) - You can see more posts by clicking 'Screen Options' at the top right of the view and increasing the number of items per page</li>\n<li>Click the down arrow next to 'Bulk Actions' and select edit</li>\n<li>Press 'Apply' - you will get a screen with a selection of changes you can make</li>\n<li>Make some change, like add a tag or change author (whatever)</li>\n<li>Press 'Update'</li>\n</ol>\n\n<p>That should do it.</p>\n\n<p>The 'difficult' way:</p>\n\n<p>In case anyone wants to use the code solution, you can add the code below to the functions.php file in your child theme.</p>\n\n<pre><code>function my_update_posts() {\n //$myposts = get_posts('showposts=-1');//Retrieve the posts you are targeting\n $args = array(\n 'post_type' =&gt; 'post',\n 'numberposts' =&gt; -1\n );\n $myposts = get_posts($args);\n foreach ($myposts as $mypost){\n $mypost-&gt;post_title = $mypost-&gt;post_title.'';\n wp_update_post( $mypost );\n }\n}\nadd_action( 'wp_loaded', 'my_update_posts' );\n</code></pre>\n\n<p>Remember to run this only once and then remove it or comment out the add_action line otherwise it will run every time a new page is loaded.</p>\n\n<p>I included this option in case anyone wants a start template for updating all post titles or some other property in all posts.</p>\n" }, { "answer_id": 294581, "author": "Maxim Sarandi", "author_id": 135962, "author_profile": "https://wordpress.stackexchange.com/users/135962", "pm_score": 2, "selected": false, "text": "<p>First: Get all posts using <code>get_posts</code> or <code>WP_Query</code>.</p>\n\n<pre><code>$query_posts = new WP_Query( array(\n 'nopaging' =&gt; true,\n) );\n</code></pre>\n\n<p>Second: Do loop for posts and use <code>wp_update_post()</code> for each post and set ID parameter.</p>\n\n<pre><code>while ( $query_posts-&gt;have_posts() ) :\n $query_posts-&gt;the_post();\n wp_update_post( array(\n 'ID' =&gt; get_the_ID(),\n 'post_content' =&gt; get_the_content(),\n ) );\nendwhile;\n</code></pre>\n\n<p>Place this code to init action or header/footer. Update page once and remove code. Place this code in <strong>functions.php</strong> and all your posts will be updated on page reload.</p>\n\n<pre><code>add_action( 'init', function () {\n $query_posts = new WP_Query( array(\n 'nopaging' =&gt; true,\n ) );\n\n while ( $query_posts-&gt;have_posts() ) :\n $query_posts-&gt;the_post();\n wp_update_post( $post );\n endwhile;\n wp_reset_postdata();\n} );\n</code></pre>\n" }, { "answer_id": 360135, "author": "Rol", "author_id": 183898, "author_profile": "https://wordpress.stackexchange.com/users/183898", "pm_score": 0, "selected": false, "text": "<p>For any future interested people: to bulk update posts one by one, you can use chrome extension web scrapper that will automatize clics on update button on every post. </p>\n" } ]
2018/02/20
[ "https://wordpress.stackexchange.com/questions/294575", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137182/" ]
I recently imported large number of custom posts into wordpress. all works fine, except one taxonomy which is imported, but not show at the front end, until i click on every post "update" button. I have 810 posts and this is not a solution... i think it should be the way to run MYSQL command to force all post update without making any changes. Please help me with command, i searched for plugins and cannot find anything suitable Thank you
There are 2 ways that you could do this. The first and more difficult is to write a program, the other is to do a bulk update. Why do difficult when easy way will work equally well? and especially as this is a once-off requirement The easy way: 1. In the admin dashboard, select the view with all posts for your custom type 2. Select all the posts (tick them) - You can see more posts by clicking 'Screen Options' at the top right of the view and increasing the number of items per page 3. Click the down arrow next to 'Bulk Actions' and select edit 4. Press 'Apply' - you will get a screen with a selection of changes you can make 5. Make some change, like add a tag or change author (whatever) 6. Press 'Update' That should do it. The 'difficult' way: In case anyone wants to use the code solution, you can add the code below to the functions.php file in your child theme. ``` function my_update_posts() { //$myposts = get_posts('showposts=-1');//Retrieve the posts you are targeting $args = array( 'post_type' => 'post', 'numberposts' => -1 ); $myposts = get_posts($args); foreach ($myposts as $mypost){ $mypost->post_title = $mypost->post_title.''; wp_update_post( $mypost ); } } add_action( 'wp_loaded', 'my_update_posts' ); ``` Remember to run this only once and then remove it or comment out the add\_action line otherwise it will run every time a new page is loaded. I included this option in case anyone wants a start template for updating all post titles or some other property in all posts.
294,582
<p><a href="https://codex.wordpress.org/index.php?title=Creating_Options_Pages&amp;oldid=97268" rel="nofollow noreferrer">https://codex.wordpress.org/index.php?title=Creating_Options_Pages&amp;oldid=97268</a></p> <p>This page shows how to create options pages.</p> <pre><code> // theme-settings.php &lt;?php add_action('admin_menu', 'talimiboard_register_menu_and_page'); function talimiboard_register_menu_and_page() { add_theme_page('Talimiboard theme settings', 'Theme Settings', 'administrator', 'talimiboard_theme_settings', 'talimiboard_theme_settings'); add_action('admin_init', 'talimiboard_register_theme_settings'); } function talimiboard_register_theme_settings() { register_setting('talimiboard_theme_settings', 'talimi_mapapi'); register_setting('talimiboard_theme_settings', 'talimi_smtphost'); register_setting('talimiboard_theme_settings', 'talimi_smtpport'); register_setting('talimiboard_theme_settings', 'talimi_smtpuser'); register_setting('talimiboard_theme_settings', 'talimi_smtppass'); register_setting('talimiboard_theme_settings', 'talimi_smtpfrom'); register_setting('talimiboard_theme_settings', 'talimi_parallax'); } function talimiboard_theme_settings() { ?&gt; &lt;style&gt; th { text-align: left; } .table-wrap { margin-top: 35px; } &lt;/style&gt; &lt;div class="wrap"&gt; &lt;h2 style="text-align: center;"&gt;Theme Settings&lt;/h2&gt; &lt;form method="post" action="options.php"&gt; &lt;?php settings_fields('talimiboard_theme_settings'); ?&gt; &lt;div class="table-wrap"&gt; &lt;h3&gt;Appearances&lt;/h3&gt; &lt;table class="form-table"&gt; &lt;tr valign="top"&gt; &lt;th scope="row"&gt;&lt;label for="talimi_parallax"&gt;Homepage Parallax Effect&lt;/label&gt;&lt;/th&gt; &lt;td&gt;&lt;input type="checkbox" id="talimi_parallax" name="talimi_parallax" value="1" &lt;?php echo checked('1', get_option('talimi_parallax')); ?&gt;/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;div class="table-wrap"&gt; &lt;h3&gt;API Keys&lt;/h3&gt; &lt;table&gt; &lt;tr valign="top"&gt; &lt;th scope="row"&gt;Google Map API Key&lt;/th&gt; &lt;td&gt;&lt;input type="text" name="talimi_mapapi" value="&lt;?php echo get_option('talimi_mapapi'); ?&gt;"/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;div class="table-wrap"&gt; &lt;h3&gt;SMTP Settings&lt;/h3&gt; &lt;table&gt; &lt;tr valign="top"&gt; &lt;th scope="row"&gt;SMTP Host&lt;/th&gt; &lt;td&gt; &lt;input type="text" name="talimi_smtphost" value="&lt;?php echo get_option('talimi_smtphost'); ?&gt;"/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th scope="row"&gt;SMTP Port&lt;/th&gt; &lt;td&gt; &lt;input type="text" name="talimi_smtpport" value="&lt;?php echo get_option('talimi_smtpport', 587); ?&gt;"/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;From&lt;/th&gt; &lt;td&gt; &lt;input type="text" name="talimi_smtpfrom" value="&lt;?php echo get_option('talimi_smtpfrom'); ?&gt;"/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;SMTP Account&lt;/th&gt; &lt;td&gt;&lt;input type="text" name="talimi_smtpuser" value="&lt;?php echo get_option('talimi_smtpuser'); ?&gt;"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;Password&lt;/th&gt; &lt;td&gt;&lt;input type="password" name="talimi_smtppass" value="&lt;?php echo get_option('talimi_smtppass'); ?&gt;"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;p class="submit"&gt; &lt;input type="submit" class="button-primary" value="&lt;?php _e('Save Changes') ?&gt;"/&gt; &lt;/p&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;?php // functions.php require_once(get_template_directory_ur() . '/page-templates/theme-settings.php'); $google_map_api_key = get_option('talimi_mapapi'); ?&gt; </code></pre> <p>Then echo $google_map_api_key shows nothing..</p>
[ { "answer_id": 294579, "author": "Clinton", "author_id": 122375, "author_profile": "https://wordpress.stackexchange.com/users/122375", "pm_score": 3, "selected": false, "text": "<p>There are 2 ways that you could do this. The first and more difficult is to write a program, the other is to do a bulk update. Why do difficult when easy way will work equally well? and especially as this is a once-off requirement</p>\n\n<p>The easy way:</p>\n\n<ol>\n<li>In the admin dashboard, select the view with all posts for your custom type</li>\n<li>Select all the posts (tick them) - You can see more posts by clicking 'Screen Options' at the top right of the view and increasing the number of items per page</li>\n<li>Click the down arrow next to 'Bulk Actions' and select edit</li>\n<li>Press 'Apply' - you will get a screen with a selection of changes you can make</li>\n<li>Make some change, like add a tag or change author (whatever)</li>\n<li>Press 'Update'</li>\n</ol>\n\n<p>That should do it.</p>\n\n<p>The 'difficult' way:</p>\n\n<p>In case anyone wants to use the code solution, you can add the code below to the functions.php file in your child theme.</p>\n\n<pre><code>function my_update_posts() {\n //$myposts = get_posts('showposts=-1');//Retrieve the posts you are targeting\n $args = array(\n 'post_type' =&gt; 'post',\n 'numberposts' =&gt; -1\n );\n $myposts = get_posts($args);\n foreach ($myposts as $mypost){\n $mypost-&gt;post_title = $mypost-&gt;post_title.'';\n wp_update_post( $mypost );\n }\n}\nadd_action( 'wp_loaded', 'my_update_posts' );\n</code></pre>\n\n<p>Remember to run this only once and then remove it or comment out the add_action line otherwise it will run every time a new page is loaded.</p>\n\n<p>I included this option in case anyone wants a start template for updating all post titles or some other property in all posts.</p>\n" }, { "answer_id": 294581, "author": "Maxim Sarandi", "author_id": 135962, "author_profile": "https://wordpress.stackexchange.com/users/135962", "pm_score": 2, "selected": false, "text": "<p>First: Get all posts using <code>get_posts</code> or <code>WP_Query</code>.</p>\n\n<pre><code>$query_posts = new WP_Query( array(\n 'nopaging' =&gt; true,\n) );\n</code></pre>\n\n<p>Second: Do loop for posts and use <code>wp_update_post()</code> for each post and set ID parameter.</p>\n\n<pre><code>while ( $query_posts-&gt;have_posts() ) :\n $query_posts-&gt;the_post();\n wp_update_post( array(\n 'ID' =&gt; get_the_ID(),\n 'post_content' =&gt; get_the_content(),\n ) );\nendwhile;\n</code></pre>\n\n<p>Place this code to init action or header/footer. Update page once and remove code. Place this code in <strong>functions.php</strong> and all your posts will be updated on page reload.</p>\n\n<pre><code>add_action( 'init', function () {\n $query_posts = new WP_Query( array(\n 'nopaging' =&gt; true,\n ) );\n\n while ( $query_posts-&gt;have_posts() ) :\n $query_posts-&gt;the_post();\n wp_update_post( $post );\n endwhile;\n wp_reset_postdata();\n} );\n</code></pre>\n" }, { "answer_id": 360135, "author": "Rol", "author_id": 183898, "author_profile": "https://wordpress.stackexchange.com/users/183898", "pm_score": 0, "selected": false, "text": "<p>For any future interested people: to bulk update posts one by one, you can use chrome extension web scrapper that will automatize clics on update button on every post. </p>\n" } ]
2018/02/20
[ "https://wordpress.stackexchange.com/questions/294582", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137188/" ]
<https://codex.wordpress.org/index.php?title=Creating_Options_Pages&oldid=97268> This page shows how to create options pages. ``` // theme-settings.php <?php add_action('admin_menu', 'talimiboard_register_menu_and_page'); function talimiboard_register_menu_and_page() { add_theme_page('Talimiboard theme settings', 'Theme Settings', 'administrator', 'talimiboard_theme_settings', 'talimiboard_theme_settings'); add_action('admin_init', 'talimiboard_register_theme_settings'); } function talimiboard_register_theme_settings() { register_setting('talimiboard_theme_settings', 'talimi_mapapi'); register_setting('talimiboard_theme_settings', 'talimi_smtphost'); register_setting('talimiboard_theme_settings', 'talimi_smtpport'); register_setting('talimiboard_theme_settings', 'talimi_smtpuser'); register_setting('talimiboard_theme_settings', 'talimi_smtppass'); register_setting('talimiboard_theme_settings', 'talimi_smtpfrom'); register_setting('talimiboard_theme_settings', 'talimi_parallax'); } function talimiboard_theme_settings() { ?> <style> th { text-align: left; } .table-wrap { margin-top: 35px; } </style> <div class="wrap"> <h2 style="text-align: center;">Theme Settings</h2> <form method="post" action="options.php"> <?php settings_fields('talimiboard_theme_settings'); ?> <div class="table-wrap"> <h3>Appearances</h3> <table class="form-table"> <tr valign="top"> <th scope="row"><label for="talimi_parallax">Homepage Parallax Effect</label></th> <td><input type="checkbox" id="talimi_parallax" name="talimi_parallax" value="1" <?php echo checked('1', get_option('talimi_parallax')); ?>/></td> </tr> </table> </div> <div class="table-wrap"> <h3>API Keys</h3> <table> <tr valign="top"> <th scope="row">Google Map API Key</th> <td><input type="text" name="talimi_mapapi" value="<?php echo get_option('talimi_mapapi'); ?>"/> </td> </tr> </table> </div> <div class="table-wrap"> <h3>SMTP Settings</h3> <table> <tr valign="top"> <th scope="row">SMTP Host</th> <td> <input type="text" name="talimi_smtphost" value="<?php echo get_option('talimi_smtphost'); ?>"/> </td> </tr> <tr> <th scope="row">SMTP Port</th> <td> <input type="text" name="talimi_smtpport" value="<?php echo get_option('talimi_smtpport', 587); ?>"/> </td> </tr> <tr> <th>From</th> <td> <input type="text" name="talimi_smtpfrom" value="<?php echo get_option('talimi_smtpfrom'); ?>"/> </td> </tr> <tr> <th>SMTP Account</th> <td><input type="text" name="talimi_smtpuser" value="<?php echo get_option('talimi_smtpuser'); ?>"/></td> </tr> <tr> <th>Password</th> <td><input type="password" name="talimi_smtppass" value="<?php echo get_option('talimi_smtppass'); ?>"/></td> </tr> </table> </div> <p class="submit"> <input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>"/> </p> </form> </div> <?php } ?> <?php // functions.php require_once(get_template_directory_ur() . '/page-templates/theme-settings.php'); $google_map_api_key = get_option('talimi_mapapi'); ?> ``` Then echo $google\_map\_api\_key shows nothing..
There are 2 ways that you could do this. The first and more difficult is to write a program, the other is to do a bulk update. Why do difficult when easy way will work equally well? and especially as this is a once-off requirement The easy way: 1. In the admin dashboard, select the view with all posts for your custom type 2. Select all the posts (tick them) - You can see more posts by clicking 'Screen Options' at the top right of the view and increasing the number of items per page 3. Click the down arrow next to 'Bulk Actions' and select edit 4. Press 'Apply' - you will get a screen with a selection of changes you can make 5. Make some change, like add a tag or change author (whatever) 6. Press 'Update' That should do it. The 'difficult' way: In case anyone wants to use the code solution, you can add the code below to the functions.php file in your child theme. ``` function my_update_posts() { //$myposts = get_posts('showposts=-1');//Retrieve the posts you are targeting $args = array( 'post_type' => 'post', 'numberposts' => -1 ); $myposts = get_posts($args); foreach ($myposts as $mypost){ $mypost->post_title = $mypost->post_title.''; wp_update_post( $mypost ); } } add_action( 'wp_loaded', 'my_update_posts' ); ``` Remember to run this only once and then remove it or comment out the add\_action line otherwise it will run every time a new page is loaded. I included this option in case anyone wants a start template for updating all post titles or some other property in all posts.
294,600
<p>I need to use Paper.js (<a href="http://paperjs.org/" rel="nofollow noreferrer">http://paperjs.org/</a>), and specifically one of their examples (<a href="http://paperjs.org/examples/smoothing/" rel="nofollow noreferrer">http://paperjs.org/examples/smoothing/</a>) on a WordPress website.</p> <p>Usually, scripts are enqued to WP with a PHP function that adds scripts of type text/javascript (<a href="https://developer.wordpress.org/reference/functions/wp_enqueue_script/" rel="nofollow noreferrer">https://developer.wordpress.org/reference/functions/wp_enqueue_script/</a>) and should be fine for the Paper.js library itself.</p> <p>But... The script utilizing Paper.js should be of type text/paperscript (<a href="http://paperjs.org/tutorials/getting-started/working-with-paper-js/" rel="nofollow noreferrer">http://paperjs.org/tutorials/getting-started/working-with-paper-js/</a>), and the only solution I could come up with is echo both script tags to my (child theme to a Genesis Framework) header.php file:</p> <pre><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.11.5/paper-full.min.js" integrity="sha256-qZnxjtwxg51juOcYyANvBWwFoahMFNB2GSkGI5LGmW0=" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script type='text/paperscript' canvas='smoothCanvas' href='../js/smoothing.js'&gt;&lt;/script&gt; </code></pre> <p>Is there any other solution? I tried to search some tutorials for Paper.js on Wordpress, but couldn't find anything.</p>
[ { "answer_id": 294629, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": true, "text": "<p>I'm not sure if this will solve your problem, but you can use the <code>script_loader_tag</code> filter to change the type <code>text/javascript</code> to <code>text/paperscript</code></p>\n\n<pre><code>add_filter( 'script_loader_tag', function( $tag, $handle, $src ) {\n if( 'your-script-handle' === $handle ) {\n $tag = str_replace( 'text/javascript', 'text/paperscript ', $tag );\n }\n return $tag;\n}, 10, 3 );\n</code></pre>\n" }, { "answer_id": 370904, "author": "Flemming", "author_id": 180483, "author_profile": "https://wordpress.stackexchange.com/users/180483", "pm_score": 1, "selected": false, "text": "<p>Or in case there's no <code>text/javascript</code> :</p>\n<pre><code>add_filter( 'script_loader_tag', function( $tag, $handle, $src ) { \n if( 'script_handle' === $handle ) {\n $tag = str_replace( '&lt;script', '&lt;script type=&quot;text/paperscript&quot; ', $tag );\n }\n return $tag;\n}, 10, 3 );\n</code></pre>\n" } ]
2018/02/20
[ "https://wordpress.stackexchange.com/questions/294600", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128875/" ]
I need to use Paper.js (<http://paperjs.org/>), and specifically one of their examples (<http://paperjs.org/examples/smoothing/>) on a WordPress website. Usually, scripts are enqued to WP with a PHP function that adds scripts of type text/javascript (<https://developer.wordpress.org/reference/functions/wp_enqueue_script/>) and should be fine for the Paper.js library itself. But... The script utilizing Paper.js should be of type text/paperscript (<http://paperjs.org/tutorials/getting-started/working-with-paper-js/>), and the only solution I could come up with is echo both script tags to my (child theme to a Genesis Framework) header.php file: ``` <script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.11.5/paper-full.min.js" integrity="sha256-qZnxjtwxg51juOcYyANvBWwFoahMFNB2GSkGI5LGmW0=" crossorigin="anonymous"></script> <script type='text/paperscript' canvas='smoothCanvas' href='../js/smoothing.js'></script> ``` Is there any other solution? I tried to search some tutorials for Paper.js on Wordpress, but couldn't find anything.
I'm not sure if this will solve your problem, but you can use the `script_loader_tag` filter to change the type `text/javascript` to `text/paperscript` ``` add_filter( 'script_loader_tag', function( $tag, $handle, $src ) { if( 'your-script-handle' === $handle ) { $tag = str_replace( 'text/javascript', 'text/paperscript ', $tag ); } return $tag; }, 10, 3 ); ```
294,612
<p>I have a custom post type named houses. Inside my custom post type I have several custom fields which I created using ACF.</p> <p>What I need to do is to change the permalink when I create a new post.</p> <p>I would like to use the <strong>code</strong> and <strong>title</strong> fields to customize the permalink:</p> <pre><code>//code + post title 4563312-house-example-1 </code></pre> <p>I'm developing a plugin which controls everything.</p> <p>Is there a way to intermediate the creation of a post to update its permalink?</p> <p>Thanks.</p>
[ { "answer_id": 294629, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": true, "text": "<p>I'm not sure if this will solve your problem, but you can use the <code>script_loader_tag</code> filter to change the type <code>text/javascript</code> to <code>text/paperscript</code></p>\n\n<pre><code>add_filter( 'script_loader_tag', function( $tag, $handle, $src ) {\n if( 'your-script-handle' === $handle ) {\n $tag = str_replace( 'text/javascript', 'text/paperscript ', $tag );\n }\n return $tag;\n}, 10, 3 );\n</code></pre>\n" }, { "answer_id": 370904, "author": "Flemming", "author_id": 180483, "author_profile": "https://wordpress.stackexchange.com/users/180483", "pm_score": 1, "selected": false, "text": "<p>Or in case there's no <code>text/javascript</code> :</p>\n<pre><code>add_filter( 'script_loader_tag', function( $tag, $handle, $src ) { \n if( 'script_handle' === $handle ) {\n $tag = str_replace( '&lt;script', '&lt;script type=&quot;text/paperscript&quot; ', $tag );\n }\n return $tag;\n}, 10, 3 );\n</code></pre>\n" } ]
2018/02/20
[ "https://wordpress.stackexchange.com/questions/294612", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133606/" ]
I have a custom post type named houses. Inside my custom post type I have several custom fields which I created using ACF. What I need to do is to change the permalink when I create a new post. I would like to use the **code** and **title** fields to customize the permalink: ``` //code + post title 4563312-house-example-1 ``` I'm developing a plugin which controls everything. Is there a way to intermediate the creation of a post to update its permalink? Thanks.
I'm not sure if this will solve your problem, but you can use the `script_loader_tag` filter to change the type `text/javascript` to `text/paperscript` ``` add_filter( 'script_loader_tag', function( $tag, $handle, $src ) { if( 'your-script-handle' === $handle ) { $tag = str_replace( 'text/javascript', 'text/paperscript ', $tag ); } return $tag; }, 10, 3 ); ```
294,613
<p>I'm creating a plugin that supports internationalization.</p> <p>Everything is working fine, except for global variables.</p> <p>Strings in global variables will not get the appropriate translation.</p> <p>Explanation:</p> <pre><code>_e('Hello World','text-domain'); // Gets translated $var = __('Hello Global World','text-domain'); function fun() { global $var; echo $var; // Doesn't get translated } </code></pre> <p>Any clue on how to fix this behaviour?</p> <p>Update: There is a similar issue, without answer, in this question <a href="https://wordpress.stackexchange.com/questions/95231/wordpress-localization-and-templating">Wordpress Localization and Templating</a></p>
[ { "answer_id": 294618, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>In general you should not have global variables.</p>\n\n<p>Specifically, if your file is not loaded at the global scope <code>$var</code> is not going o be global unless you explicitly declare it as such. Your problem is unlikely to be related to the actual translation.</p>\n" }, { "answer_id": 294636, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 1, "selected": true, "text": "<p>Translation works with global variables, you just need to wait until the proper hook to call the translation functions. I haven't looked at the code or documentation, but just by experimenting, the translations are loaded sometime before the <code>after_setup_theme</code> hook, but after the other hooks that fire before that.</p>\n\n<p>That means that if you try to translate something on the <code>plugins_loaded</code> hook, you're not going to get a translated result back.</p>\n\n<p>As an example, in the following plugin, the first time <code>$dash</code> is \"translated\" in the main plugin file, it won't be. It will always print \"Dashboard\" no matter what. Same thing on the <code>plugins_loaded</code> hook.</p>\n\n<p>The fun part is in the <code>after_setup_theme</code> hook where the global <code>$dash</code> prints in English, but the newly translated text prints (in my case) \"Escritorio\".</p>\n\n<p>On the <code>init</code> hook, the global <code>$dash</code> prints the translated text. I added a callback to a closure to make sure that it was displaying the global <code>$dash</code> variable, and it was.</p>\n\n<pre><code>/**\n * Plugin Name: StackExchange Sample\n */\n\nnamespace StackExchange\\WordPress;\n\n$dash = __( 'Dashboard ' );\nprintf( '&lt;p&gt;Main plugin file: %1$s&lt;/p&gt;', $dash ); // Dashboard\n\nclass plugin {\n public function plugins_loaded() {\n \\add_action( 'after_setup_theme', [ $this, 'after_setup_theme' ] );\n \\add_action( 'init', [ $this, 'init' ] );\n\n echo '&lt;h2&gt;plugins_loaded&lt;/h2&gt;';\n global $dash;\n printf( '&lt;p&gt;Global: %1$s&lt;/p&gt;', $dash ); // Dashboard\n $dash = __( 'Dashboard' );\n printf( '&lt;p&gt;Local: %1$s&lt;/p&gt;', $dash ); // Dashboard\n }\n public function after_setup_theme() {\n echo '&lt;h2&gt;after_setup_theme&lt;/h2&gt;';\n global $dash;\n printf( '&lt;p&gt;Global: %1$s&lt;/p&gt;', $dash ); // Dashboard\n $dash = __( 'Dashboard' );\n printf( '&lt;p&gt;Local: %1$s&lt;/p&gt;', $dash ); // Escritorio\n }\n public function init() {\n echo '&lt;h2&gt;init&lt;/h2&gt;';\n global $dash;\n printf( '&lt;p&gt;Global: %1$s&lt;/p&gt;', $dash ); // Escritorio\n $dash = __( 'Dashboard' );\n printf( '&lt;p&gt;Local: %1$s&lt;/p&gt;', $dash ); // Escritorio\n }\n}\n\\add_action( 'plugins_loaded', [ new plugin(), 'plugins_loaded' ] );\n\\add_action( 'init', function() {\n global $dash;\n printf( '&lt;p&gt;Global: %1$s&lt;/p&gt;', $dash ); // Escritorio\n}, 20 );\n</code></pre>\n\n<p>In summation: global variables with translated text do work, make sure you wait until after the <code>after_setup_theme</code> hook to translate your text, and don't use global variables because it'll just cause problems.</p>\n" } ]
2018/02/20
[ "https://wordpress.stackexchange.com/questions/294613", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109855/" ]
I'm creating a plugin that supports internationalization. Everything is working fine, except for global variables. Strings in global variables will not get the appropriate translation. Explanation: ``` _e('Hello World','text-domain'); // Gets translated $var = __('Hello Global World','text-domain'); function fun() { global $var; echo $var; // Doesn't get translated } ``` Any clue on how to fix this behaviour? Update: There is a similar issue, without answer, in this question [Wordpress Localization and Templating](https://wordpress.stackexchange.com/questions/95231/wordpress-localization-and-templating)
Translation works with global variables, you just need to wait until the proper hook to call the translation functions. I haven't looked at the code or documentation, but just by experimenting, the translations are loaded sometime before the `after_setup_theme` hook, but after the other hooks that fire before that. That means that if you try to translate something on the `plugins_loaded` hook, you're not going to get a translated result back. As an example, in the following plugin, the first time `$dash` is "translated" in the main plugin file, it won't be. It will always print "Dashboard" no matter what. Same thing on the `plugins_loaded` hook. The fun part is in the `after_setup_theme` hook where the global `$dash` prints in English, but the newly translated text prints (in my case) "Escritorio". On the `init` hook, the global `$dash` prints the translated text. I added a callback to a closure to make sure that it was displaying the global `$dash` variable, and it was. ``` /** * Plugin Name: StackExchange Sample */ namespace StackExchange\WordPress; $dash = __( 'Dashboard ' ); printf( '<p>Main plugin file: %1$s</p>', $dash ); // Dashboard class plugin { public function plugins_loaded() { \add_action( 'after_setup_theme', [ $this, 'after_setup_theme' ] ); \add_action( 'init', [ $this, 'init' ] ); echo '<h2>plugins_loaded</h2>'; global $dash; printf( '<p>Global: %1$s</p>', $dash ); // Dashboard $dash = __( 'Dashboard' ); printf( '<p>Local: %1$s</p>', $dash ); // Dashboard } public function after_setup_theme() { echo '<h2>after_setup_theme</h2>'; global $dash; printf( '<p>Global: %1$s</p>', $dash ); // Dashboard $dash = __( 'Dashboard' ); printf( '<p>Local: %1$s</p>', $dash ); // Escritorio } public function init() { echo '<h2>init</h2>'; global $dash; printf( '<p>Global: %1$s</p>', $dash ); // Escritorio $dash = __( 'Dashboard' ); printf( '<p>Local: %1$s</p>', $dash ); // Escritorio } } \add_action( 'plugins_loaded', [ new plugin(), 'plugins_loaded' ] ); \add_action( 'init', function() { global $dash; printf( '<p>Global: %1$s</p>', $dash ); // Escritorio }, 20 ); ``` In summation: global variables with translated text do work, make sure you wait until after the `after_setup_theme` hook to translate your text, and don't use global variables because it'll just cause problems.
294,623
<p>I am trying to use the jQuery Datatables plugin in my WordPress dashboard but the native WordPress admin CSS styling is overiding the datatables CSS, I am calling them like this...</p> <pre><code>add_action('admin_enqueue_scripts', 'admin_scripts'); function admin_scripts() { wp_enqueue_script('datatables', '//cdn.datatables.net/v/bs4/dt-1.10.16/datatables.min.js', array('jquery'),'1.21', true ); wp_enqueue_style('datatables-css', '//cdn.datatables.net/v/bs4/dt-1.10.16/datatables.min.css', 99); } </code></pre> <p>Is there a way to change the priority so it loads the datatables CSS first?</p>
[ { "answer_id": 294624, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": 1, "selected": false, "text": "<p>By default they should already be loading after the core admin styles. I suspect the CSS isn't even being loaded because you have an invalid parameter in your <code>wp_enqueue_style()</code> call. Its parameters are the same as <code>wp_enqueue_script()</code>. Where you have <code>99</code> is where dependencies are actually defined. So WordPress is looking for <code>99</code> to be loaded, not finding it, and skipping the enqueue.</p>\n\n<p>So I would re-write that as follows:</p>\n\n<pre><code> wp_enqueue_style( 'datatables-css', '//cdn.datatables.net/v/bs4/dt-1.10.16/datatables.min.css', 'datatables' );\n</code></pre>\n\n<p>What this does is loads the stylesheet but only if the JavaScript file is loaded.</p>\n" }, { "answer_id": 294709, "author": "Peter HvD", "author_id": 134918, "author_profile": "https://wordpress.stackexchange.com/users/134918", "pm_score": 0, "selected": false, "text": "<p>You don't need to do that as this is all about CSS specificity. What you need to do is wrap the datatable in a unique div and then use that to specifically target the elements in your CSS.</p>\n\n<p>For example (I don't know the CSS, BTW, so this is just a general example)</p>\n\n<p>Wrap the table element in <code>&lt;div class=\"myClass\"&gt;</code></p>\n\n<p>Use the Inspector in your browser to find out exactly what line of CSS is being used for the styling you want to override. </p>\n\n<p>If the CSS for an element is <code>table.dataTable tr.dataTr td.dataTd</code> then if you add the wrapper div to that it should override it as it's more specific, ie: <code>.myClass table.dataTable tr.dataTr td.dataTd</code></p>\n\n<p>You might need to experiment a bit until you get exactly the right combination to override the specificity. I usually find a wrapper element is enough, but sometimes I find adding a specific class to the (eg)table element helps (if you can), so it might be: <code>table.dataTable.myTableClass tr.dataTr td.dataTd</code></p>\n\n<p>Hope that helps</p>\n" } ]
2018/02/20
[ "https://wordpress.stackexchange.com/questions/294623", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10247/" ]
I am trying to use the jQuery Datatables plugin in my WordPress dashboard but the native WordPress admin CSS styling is overiding the datatables CSS, I am calling them like this... ``` add_action('admin_enqueue_scripts', 'admin_scripts'); function admin_scripts() { wp_enqueue_script('datatables', '//cdn.datatables.net/v/bs4/dt-1.10.16/datatables.min.js', array('jquery'),'1.21', true ); wp_enqueue_style('datatables-css', '//cdn.datatables.net/v/bs4/dt-1.10.16/datatables.min.css', 99); } ``` Is there a way to change the priority so it loads the datatables CSS first?
By default they should already be loading after the core admin styles. I suspect the CSS isn't even being loaded because you have an invalid parameter in your `wp_enqueue_style()` call. Its parameters are the same as `wp_enqueue_script()`. Where you have `99` is where dependencies are actually defined. So WordPress is looking for `99` to be loaded, not finding it, and skipping the enqueue. So I would re-write that as follows: ``` wp_enqueue_style( 'datatables-css', '//cdn.datatables.net/v/bs4/dt-1.10.16/datatables.min.css', 'datatables' ); ``` What this does is loads the stylesheet but only if the JavaScript file is loaded.
294,644
<p>First, sorry my english. I am using Local by flywheel to manager my site files and my wordpress version is 4.9.4.</p> <p>Here is the problem, When I use</p> <pre><code> wp_enqueue_style('wharever', get_stylesheet_uri()); </code></pre> <p>To load style.css at the first time with a just simple content inside:</p> <pre><code>body { color: orange; } </code></pre> <p>Everything is just fine, and we have a page with everything in orange text, but when I change the style.css body color to green (or whatever), they just don't change, and always are orange.</p> <p>PS.: in wp_enqueue_style, I changed the version parameter and he changes, but only at the first time and stuck with the first color I put for the version that was put.</p> <p>If this is a feature of wordpress, how can I turn this off? This don't see quite useful know that we can't change style.css at will just to test without change version.</p>
[ { "answer_id": 294656, "author": "n8bar", "author_id": 116579, "author_profile": "https://wordpress.stackexchange.com/users/116579", "pm_score": 1, "selected": false, "text": "<p>It is a caching problem. To get around this I append a random string to the stylesheet uri that discourages the browser from caching it.</p>\n\n<p>First you need a random string. I use this simple function to generate one.</p>\n\n<p><code>function randomAlphaNumeric($length) {\n $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));\n $key='';\n for($i=0; $i &lt; $length; $i++) {\n $key .= $pool[mt_rand(0, count($pool) - 1)];\n }\n return $key;\n}\n</code></p>\n\n<p>Now just use it in your enqueue like this:</p>\n\n<p><code>wp_enqueue_style('wharever', get_stylesheet_uri().'?random='.randomAlphaNumeric(5));</code></p>\n" }, { "answer_id": 294663, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 3, "selected": true, "text": "<p>Another solution is to use <code>filemtime</code> for the cachebusting, so that the last modified timestamp is used as the querystring variable. </p>\n\n<p>This has the advantage that of still using the browser cache, and yet, a new file is served when the file is actually changed because the querystring changes. eg.</p>\n\n<pre><code>$lastmodtime= filemtime(get_stylesheet_directory().'/style.css');\nwp_enqueue_style('whatever', get_stylesheet_uri(), array(), $lastmodtime);\n</code></pre>\n" }, { "answer_id": 360869, "author": "Vala Khosravi", "author_id": 184264, "author_profile": "https://wordpress.stackexchange.com/users/184264", "pm_score": 1, "selected": false, "text": "<p>You can change your </p>\n\n<pre><code> wp_enqueue_style('wharever', get_stylesheet_uri());\n</code></pre>\n\n<p>to </p>\n\n<pre><code> wp_enqueue_style('wharever', get_stylesheet_uri(), array(), time(), 'all');\n</code></pre>\n\n<p>And it will start working just fine.</p>\n" } ]
2018/02/20
[ "https://wordpress.stackexchange.com/questions/294644", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137223/" ]
First, sorry my english. I am using Local by flywheel to manager my site files and my wordpress version is 4.9.4. Here is the problem, When I use ``` wp_enqueue_style('wharever', get_stylesheet_uri()); ``` To load style.css at the first time with a just simple content inside: ``` body { color: orange; } ``` Everything is just fine, and we have a page with everything in orange text, but when I change the style.css body color to green (or whatever), they just don't change, and always are orange. PS.: in wp\_enqueue\_style, I changed the version parameter and he changes, but only at the first time and stuck with the first color I put for the version that was put. If this is a feature of wordpress, how can I turn this off? This don't see quite useful know that we can't change style.css at will just to test without change version.
Another solution is to use `filemtime` for the cachebusting, so that the last modified timestamp is used as the querystring variable. This has the advantage that of still using the browser cache, and yet, a new file is served when the file is actually changed because the querystring changes. eg. ``` $lastmodtime= filemtime(get_stylesheet_directory().'/style.css'); wp_enqueue_style('whatever', get_stylesheet_uri(), array(), $lastmodtime); ```
294,671
<p>I made a custom post type, say ‘movie’, using "custom type post UI" plugin, and linked it with built-in category. Both normal posts and custom type posts are in the same category. My question is that if it is possible to modify the existing counting function so that it counts the number of posts that does not have a post type 'movie', i.e., only counts normal posts. </p> <p>For example, one of my category, say ‘hobby’, has 5 normal posts + 3 custom ‘movie’ posts. Then, in the category widget, I want to have something like ‘hobby (5)’, not ‘hobby (8)’. In short, If it is possible, I just want to add a function (like add_filter or add_action or etc...) in functions.php to resolve this problem.</p> <p>Thank you in advance.</p>
[ { "answer_id": 294656, "author": "n8bar", "author_id": 116579, "author_profile": "https://wordpress.stackexchange.com/users/116579", "pm_score": 1, "selected": false, "text": "<p>It is a caching problem. To get around this I append a random string to the stylesheet uri that discourages the browser from caching it.</p>\n\n<p>First you need a random string. I use this simple function to generate one.</p>\n\n<p><code>function randomAlphaNumeric($length) {\n $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));\n $key='';\n for($i=0; $i &lt; $length; $i++) {\n $key .= $pool[mt_rand(0, count($pool) - 1)];\n }\n return $key;\n}\n</code></p>\n\n<p>Now just use it in your enqueue like this:</p>\n\n<p><code>wp_enqueue_style('wharever', get_stylesheet_uri().'?random='.randomAlphaNumeric(5));</code></p>\n" }, { "answer_id": 294663, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 3, "selected": true, "text": "<p>Another solution is to use <code>filemtime</code> for the cachebusting, so that the last modified timestamp is used as the querystring variable. </p>\n\n<p>This has the advantage that of still using the browser cache, and yet, a new file is served when the file is actually changed because the querystring changes. eg.</p>\n\n<pre><code>$lastmodtime= filemtime(get_stylesheet_directory().'/style.css');\nwp_enqueue_style('whatever', get_stylesheet_uri(), array(), $lastmodtime);\n</code></pre>\n" }, { "answer_id": 360869, "author": "Vala Khosravi", "author_id": 184264, "author_profile": "https://wordpress.stackexchange.com/users/184264", "pm_score": 1, "selected": false, "text": "<p>You can change your </p>\n\n<pre><code> wp_enqueue_style('wharever', get_stylesheet_uri());\n</code></pre>\n\n<p>to </p>\n\n<pre><code> wp_enqueue_style('wharever', get_stylesheet_uri(), array(), time(), 'all');\n</code></pre>\n\n<p>And it will start working just fine.</p>\n" } ]
2018/02/21
[ "https://wordpress.stackexchange.com/questions/294671", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137244/" ]
I made a custom post type, say ‘movie’, using "custom type post UI" plugin, and linked it with built-in category. Both normal posts and custom type posts are in the same category. My question is that if it is possible to modify the existing counting function so that it counts the number of posts that does not have a post type 'movie', i.e., only counts normal posts. For example, one of my category, say ‘hobby’, has 5 normal posts + 3 custom ‘movie’ posts. Then, in the category widget, I want to have something like ‘hobby (5)’, not ‘hobby (8)’. In short, If it is possible, I just want to add a function (like add\_filter or add\_action or etc...) in functions.php to resolve this problem. Thank you in advance.
Another solution is to use `filemtime` for the cachebusting, so that the last modified timestamp is used as the querystring variable. This has the advantage that of still using the browser cache, and yet, a new file is served when the file is actually changed because the querystring changes. eg. ``` $lastmodtime= filemtime(get_stylesheet_directory().'/style.css'); wp_enqueue_style('whatever', get_stylesheet_uri(), array(), $lastmodtime); ```
294,676
<p>I have a Wordpress site, I have the Front Page settings right in the Reading settings, but when I goto my Wordpress site and I am not login, I get a 404 error and my page looks messed up. When I am login to Wordpress my Front Page looks like it should and I dont get a 404 page. Here is my site, why is this happening?</p> <p>makinghermrs.com</p> <p>Here is my .htaccess file:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>Also I am unable to change the static front page in my settings, when I save it, nothing gets changed.</p> <p>More information in another question I asked:</p> <p><a href="https://wordpress.stackexchange.com/questions/295005/issue-with-my-theme">Issue with my theme</a></p>
[ { "answer_id": 294656, "author": "n8bar", "author_id": 116579, "author_profile": "https://wordpress.stackexchange.com/users/116579", "pm_score": 1, "selected": false, "text": "<p>It is a caching problem. To get around this I append a random string to the stylesheet uri that discourages the browser from caching it.</p>\n\n<p>First you need a random string. I use this simple function to generate one.</p>\n\n<p><code>function randomAlphaNumeric($length) {\n $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));\n $key='';\n for($i=0; $i &lt; $length; $i++) {\n $key .= $pool[mt_rand(0, count($pool) - 1)];\n }\n return $key;\n}\n</code></p>\n\n<p>Now just use it in your enqueue like this:</p>\n\n<p><code>wp_enqueue_style('wharever', get_stylesheet_uri().'?random='.randomAlphaNumeric(5));</code></p>\n" }, { "answer_id": 294663, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 3, "selected": true, "text": "<p>Another solution is to use <code>filemtime</code> for the cachebusting, so that the last modified timestamp is used as the querystring variable. </p>\n\n<p>This has the advantage that of still using the browser cache, and yet, a new file is served when the file is actually changed because the querystring changes. eg.</p>\n\n<pre><code>$lastmodtime= filemtime(get_stylesheet_directory().'/style.css');\nwp_enqueue_style('whatever', get_stylesheet_uri(), array(), $lastmodtime);\n</code></pre>\n" }, { "answer_id": 360869, "author": "Vala Khosravi", "author_id": 184264, "author_profile": "https://wordpress.stackexchange.com/users/184264", "pm_score": 1, "selected": false, "text": "<p>You can change your </p>\n\n<pre><code> wp_enqueue_style('wharever', get_stylesheet_uri());\n</code></pre>\n\n<p>to </p>\n\n<pre><code> wp_enqueue_style('wharever', get_stylesheet_uri(), array(), time(), 'all');\n</code></pre>\n\n<p>And it will start working just fine.</p>\n" } ]
2018/02/21
[ "https://wordpress.stackexchange.com/questions/294676", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/19080/" ]
I have a Wordpress site, I have the Front Page settings right in the Reading settings, but when I goto my Wordpress site and I am not login, I get a 404 error and my page looks messed up. When I am login to Wordpress my Front Page looks like it should and I dont get a 404 page. Here is my site, why is this happening? makinghermrs.com Here is my .htaccess file: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` Also I am unable to change the static front page in my settings, when I save it, nothing gets changed. More information in another question I asked: [Issue with my theme](https://wordpress.stackexchange.com/questions/295005/issue-with-my-theme)
Another solution is to use `filemtime` for the cachebusting, so that the last modified timestamp is used as the querystring variable. This has the advantage that of still using the browser cache, and yet, a new file is served when the file is actually changed because the querystring changes. eg. ``` $lastmodtime= filemtime(get_stylesheet_directory().'/style.css'); wp_enqueue_style('whatever', get_stylesheet_uri(), array(), $lastmodtime); ```
294,735
<p>I have a search bar on 2 pages in my site and on my page called archive I want to exclude a category called economics (id - 9) from the search. I have placed this in my functions.php file:</p> <pre><code>function archive_search_filter( $query ) { if ( $query-&gt;is_search &amp;&amp; $query-&gt;is_main_query() ) { $query-&gt;set( 'category__not_in' , '9' ); } } add_filter( 'pre_get_posts', 'archive_search_filter' ); </code></pre> <p>and it works perfectly but I want to only have this implemented on the page called archive. If I try an if statement with is_page('archive') along with this it is not working and I'm not sure of a solution. I'm wondering if the functions.php loads before it can tell what page it is and if there is another way to get this to work.</p>
[ { "answer_id": 294656, "author": "n8bar", "author_id": 116579, "author_profile": "https://wordpress.stackexchange.com/users/116579", "pm_score": 1, "selected": false, "text": "<p>It is a caching problem. To get around this I append a random string to the stylesheet uri that discourages the browser from caching it.</p>\n\n<p>First you need a random string. I use this simple function to generate one.</p>\n\n<p><code>function randomAlphaNumeric($length) {\n $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));\n $key='';\n for($i=0; $i &lt; $length; $i++) {\n $key .= $pool[mt_rand(0, count($pool) - 1)];\n }\n return $key;\n}\n</code></p>\n\n<p>Now just use it in your enqueue like this:</p>\n\n<p><code>wp_enqueue_style('wharever', get_stylesheet_uri().'?random='.randomAlphaNumeric(5));</code></p>\n" }, { "answer_id": 294663, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 3, "selected": true, "text": "<p>Another solution is to use <code>filemtime</code> for the cachebusting, so that the last modified timestamp is used as the querystring variable. </p>\n\n<p>This has the advantage that of still using the browser cache, and yet, a new file is served when the file is actually changed because the querystring changes. eg.</p>\n\n<pre><code>$lastmodtime= filemtime(get_stylesheet_directory().'/style.css');\nwp_enqueue_style('whatever', get_stylesheet_uri(), array(), $lastmodtime);\n</code></pre>\n" }, { "answer_id": 360869, "author": "Vala Khosravi", "author_id": 184264, "author_profile": "https://wordpress.stackexchange.com/users/184264", "pm_score": 1, "selected": false, "text": "<p>You can change your </p>\n\n<pre><code> wp_enqueue_style('wharever', get_stylesheet_uri());\n</code></pre>\n\n<p>to </p>\n\n<pre><code> wp_enqueue_style('wharever', get_stylesheet_uri(), array(), time(), 'all');\n</code></pre>\n\n<p>And it will start working just fine.</p>\n" } ]
2018/02/21
[ "https://wordpress.stackexchange.com/questions/294735", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127290/" ]
I have a search bar on 2 pages in my site and on my page called archive I want to exclude a category called economics (id - 9) from the search. I have placed this in my functions.php file: ``` function archive_search_filter( $query ) { if ( $query->is_search && $query->is_main_query() ) { $query->set( 'category__not_in' , '9' ); } } add_filter( 'pre_get_posts', 'archive_search_filter' ); ``` and it works perfectly but I want to only have this implemented on the page called archive. If I try an if statement with is\_page('archive') along with this it is not working and I'm not sure of a solution. I'm wondering if the functions.php loads before it can tell what page it is and if there is another way to get this to work.
Another solution is to use `filemtime` for the cachebusting, so that the last modified timestamp is used as the querystring variable. This has the advantage that of still using the browser cache, and yet, a new file is served when the file is actually changed because the querystring changes. eg. ``` $lastmodtime= filemtime(get_stylesheet_directory().'/style.css'); wp_enqueue_style('whatever', get_stylesheet_uri(), array(), $lastmodtime); ```
294,787
<p>I have looked online and found different pieces of code together but unable to find a solution that holds up.</p> <p>Basically i need to display 10 posts in total, but the first three need to be random.</p> <p>This is what I have so far (taken from a similar question).</p> <pre><code>$args = array( 'post_type' =&gt; 'post', 'posts_per_page' =&gt; -1, 'orderby' =&gt; 'publish_date', 'order' =&gt; 'DESC', '_shuffle_and_pick' =&gt; 3 // &lt;-- our custom argument ); $loop = new \WP_Query( $args ); </code></pre> <p>With the following function in my functions.php</p> <pre><code>add_filter( 'the_posts', function( $posts, \WP_Query $query ) { if( $pick = $query-&gt;get( '_shuffle_and_pick' ) ) { shuffle( $posts ); $posts = array_slice( $posts, 0, (int) $pick ); } return $posts; }, 10, 2 ); </code></pre> <p>But this just displays three random posts and that's all.</p> <p>Can this be adapted so that the it displays 10 in total, with the first 3 being random the rest in date order?</p> <p>Or do I need a new approach?</p>
[ { "answer_id": 294788, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>Perhaps this psuedocode in the Loop:</p>\n\n<pre><code>// set up a counter\n// the WP Loop\n // if counter &lt; 4 (so first three posts)\n // put the post output text into an array element (with title, links, content, etc)\n // if counter &gt; 3 (so the next posts after the first three\n // put the post output into a different array element\n // increment the counter\n// the WP Loop end\n// now output the loop's content\n// for the elements in the first array (the first three posts)\n // output each element in the loop (each element is the post title.content/etc\n// end the first loop\n// for the elements in the 2nd array (the rest of the post)\n // output each element in the loop\n// end the second loop\n// all done\n</code></pre>\n\n<p>Very rough, but you might get the idea.</p>\n" }, { "answer_id": 294810, "author": "luukvhoudt", "author_id": 44637, "author_profile": "https://wordpress.stackexchange.com/users/44637", "pm_score": 1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>// All the rendered HTML\n$output = '';\n\n// The posts to exclude from the random query.\n$exclude = [];\n\n// The remaining non-random posts\n$remaining = new WP_Query([ \n 'posts_per_page' =&gt; 7,\n]);\n\n// Run the remaining query first because we have to know what should be excluded in the random query.\nif {$remaining-&gt;have_posts()) {\n while ($remaining-&gt;have_posts()) {\n $remaining-&gt;the_post();\n\n // Ensure that all remainig posts are excluded from the random query.\n $exclude[] = get_the_ID();\n\n ob_start();\n\n // Render the output, consider using a function for consistency.\n the_title();\n the_content();\n\n // Gather and append the ouput.\n $output .= ob_get_clean();\n }\n wp_reset_query();\n}\n\n// Setup the random query with the excluded posts array.\n$random = new WP_Query([\n 'posts_per_page' =&gt; 3,\n 'exclude' =&gt; $exclude,\n 'orderby' =&gt; 'rand',\n]);\n\n// Run the random query\nif {$random-&gt;have_posts()) {\n while ($random-&gt;have_posts()) {\n $random-&gt;the_post();\n\n ob_start();\n\n // Again render the output, consider using a function for consistency.\n the_title();\n the_content();\n\n // Gather and prepend the ouput.\n $output = ob_get_clean() . $ouput;\n }\n wp_reset_query();\n}\n\n// Display the ouput\nprint $output;\n</code></pre>\n\n<p>You could also turn it around, first run the random query and store their ids to exclude in the remainig query what runs after the random query.</p>\n\n<p>You need two loops because you can't \"include\" 3 specific posts what are shown on top of the remaining posts. However you can try doing it with one loop what returns the posts in an incorrect order but than you use grid css to change the display order.</p>\n" } ]
2018/02/21
[ "https://wordpress.stackexchange.com/questions/294787", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137320/" ]
I have looked online and found different pieces of code together but unable to find a solution that holds up. Basically i need to display 10 posts in total, but the first three need to be random. This is what I have so far (taken from a similar question). ``` $args = array( 'post_type' => 'post', 'posts_per_page' => -1, 'orderby' => 'publish_date', 'order' => 'DESC', '_shuffle_and_pick' => 3 // <-- our custom argument ); $loop = new \WP_Query( $args ); ``` With the following function in my functions.php ``` add_filter( 'the_posts', function( $posts, \WP_Query $query ) { if( $pick = $query->get( '_shuffle_and_pick' ) ) { shuffle( $posts ); $posts = array_slice( $posts, 0, (int) $pick ); } return $posts; }, 10, 2 ); ``` But this just displays three random posts and that's all. Can this be adapted so that the it displays 10 in total, with the first 3 being random the rest in date order? Or do I need a new approach?
Try this: ``` // All the rendered HTML $output = ''; // The posts to exclude from the random query. $exclude = []; // The remaining non-random posts $remaining = new WP_Query([ 'posts_per_page' => 7, ]); // Run the remaining query first because we have to know what should be excluded in the random query. if {$remaining->have_posts()) { while ($remaining->have_posts()) { $remaining->the_post(); // Ensure that all remainig posts are excluded from the random query. $exclude[] = get_the_ID(); ob_start(); // Render the output, consider using a function for consistency. the_title(); the_content(); // Gather and append the ouput. $output .= ob_get_clean(); } wp_reset_query(); } // Setup the random query with the excluded posts array. $random = new WP_Query([ 'posts_per_page' => 3, 'exclude' => $exclude, 'orderby' => 'rand', ]); // Run the random query if {$random->have_posts()) { while ($random->have_posts()) { $random->the_post(); ob_start(); // Again render the output, consider using a function for consistency. the_title(); the_content(); // Gather and prepend the ouput. $output = ob_get_clean() . $ouput; } wp_reset_query(); } // Display the ouput print $output; ``` You could also turn it around, first run the random query and store their ids to exclude in the remainig query what runs after the random query. You need two loops because you can't "include" 3 specific posts what are shown on top of the remaining posts. However you can try doing it with one loop what returns the posts in an incorrect order but than you use grid css to change the display order.
294,822
<p>I have here hardcoded category id so I can pull in needed categories and their posts by category. But ideally I would like to get this by calling parent category to list child and post. My code works but that's not how I would like to do it and would like to hear any suggestions to improve. I'm still trying to figure this out myself as well.</p> <p>Parent category is 'winners-2018'. </p> <pre><code>&lt;?php $catz = array(6012,6013,6014,6015,6016); foreach($catz as $i=&gt;$categ){ $cat_archive = get_category ($categ); //var_dump($cat_archive); global $wp_query; $args = array_merge( $wp_query-&gt;query_vars,array( 'paged'=&gt;$paged, 'posts_per_page'=&gt;10, 'post_type' =&gt; 'winners', 'category_name' =&gt; $cat_archive-&gt;slug, )); ?&gt; &lt;div class="outer"&gt; &lt;div class="inner"&gt; &lt;div class="inside"&gt; &lt;h1&gt;&lt;?php echo $cat_archive-&gt;name; ?&gt;&lt;/h1&gt; &lt;/div&gt; &lt;div class="left-content winners_fullwidth &lt;?php if(is_category()) { echo $cat_archive-&gt;slug;} ?&gt;"&gt; &lt;div class="wrap-content clearfix"&gt; &lt;?php $cposts = get_posts(array( 'category'=&gt;$categ, 'orderby' =&gt; 'title', 'order' =&gt; 'ASC', 'posts_per_page'=&gt;10, 'post_type' =&gt; 'winners', )); foreach ( $cposts as $post ) : setup_postdata( $post ); ?&gt; &lt;div class="press-box"&gt; &lt;?php if ( has_post_thumbnail() ) { ?&gt; &lt;div class="art-image"&gt; &lt;a href="&lt;?php echo get_permalink(); ?&gt;" title="&lt;?php the_title();?&gt;"&gt;&lt;?php the_post_thumbnail( 'square-blog' ); ?&gt;&lt;/a&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;div class="art-right"&gt; &lt;h2&gt;&lt;a class="perma" href="&lt;?php echo get_permalink(); ?&gt;"&gt;&lt;?php the_title();?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;?php the_excerpt();?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endforeach;?&gt; &lt;?php wp_reset_query(); ?&gt; &lt;/div&gt;&lt;!-- wrap-content --&gt; &lt;/div&gt;&lt;!-- left-content --&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre>
[ { "answer_id": 294788, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>Perhaps this psuedocode in the Loop:</p>\n\n<pre><code>// set up a counter\n// the WP Loop\n // if counter &lt; 4 (so first three posts)\n // put the post output text into an array element (with title, links, content, etc)\n // if counter &gt; 3 (so the next posts after the first three\n // put the post output into a different array element\n // increment the counter\n// the WP Loop end\n// now output the loop's content\n// for the elements in the first array (the first three posts)\n // output each element in the loop (each element is the post title.content/etc\n// end the first loop\n// for the elements in the 2nd array (the rest of the post)\n // output each element in the loop\n// end the second loop\n// all done\n</code></pre>\n\n<p>Very rough, but you might get the idea.</p>\n" }, { "answer_id": 294810, "author": "luukvhoudt", "author_id": 44637, "author_profile": "https://wordpress.stackexchange.com/users/44637", "pm_score": 1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>// All the rendered HTML\n$output = '';\n\n// The posts to exclude from the random query.\n$exclude = [];\n\n// The remaining non-random posts\n$remaining = new WP_Query([ \n 'posts_per_page' =&gt; 7,\n]);\n\n// Run the remaining query first because we have to know what should be excluded in the random query.\nif {$remaining-&gt;have_posts()) {\n while ($remaining-&gt;have_posts()) {\n $remaining-&gt;the_post();\n\n // Ensure that all remainig posts are excluded from the random query.\n $exclude[] = get_the_ID();\n\n ob_start();\n\n // Render the output, consider using a function for consistency.\n the_title();\n the_content();\n\n // Gather and append the ouput.\n $output .= ob_get_clean();\n }\n wp_reset_query();\n}\n\n// Setup the random query with the excluded posts array.\n$random = new WP_Query([\n 'posts_per_page' =&gt; 3,\n 'exclude' =&gt; $exclude,\n 'orderby' =&gt; 'rand',\n]);\n\n// Run the random query\nif {$random-&gt;have_posts()) {\n while ($random-&gt;have_posts()) {\n $random-&gt;the_post();\n\n ob_start();\n\n // Again render the output, consider using a function for consistency.\n the_title();\n the_content();\n\n // Gather and prepend the ouput.\n $output = ob_get_clean() . $ouput;\n }\n wp_reset_query();\n}\n\n// Display the ouput\nprint $output;\n</code></pre>\n\n<p>You could also turn it around, first run the random query and store their ids to exclude in the remainig query what runs after the random query.</p>\n\n<p>You need two loops because you can't \"include\" 3 specific posts what are shown on top of the remaining posts. However you can try doing it with one loop what returns the posts in an incorrect order but than you use grid css to change the display order.</p>\n" } ]
2018/02/22
[ "https://wordpress.stackexchange.com/questions/294822", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135938/" ]
I have here hardcoded category id so I can pull in needed categories and their posts by category. But ideally I would like to get this by calling parent category to list child and post. My code works but that's not how I would like to do it and would like to hear any suggestions to improve. I'm still trying to figure this out myself as well. Parent category is 'winners-2018'. ``` <?php $catz = array(6012,6013,6014,6015,6016); foreach($catz as $i=>$categ){ $cat_archive = get_category ($categ); //var_dump($cat_archive); global $wp_query; $args = array_merge( $wp_query->query_vars,array( 'paged'=>$paged, 'posts_per_page'=>10, 'post_type' => 'winners', 'category_name' => $cat_archive->slug, )); ?> <div class="outer"> <div class="inner"> <div class="inside"> <h1><?php echo $cat_archive->name; ?></h1> </div> <div class="left-content winners_fullwidth <?php if(is_category()) { echo $cat_archive->slug;} ?>"> <div class="wrap-content clearfix"> <?php $cposts = get_posts(array( 'category'=>$categ, 'orderby' => 'title', 'order' => 'ASC', 'posts_per_page'=>10, 'post_type' => 'winners', )); foreach ( $cposts as $post ) : setup_postdata( $post ); ?> <div class="press-box"> <?php if ( has_post_thumbnail() ) { ?> <div class="art-image"> <a href="<?php echo get_permalink(); ?>" title="<?php the_title();?>"><?php the_post_thumbnail( 'square-blog' ); ?></a> </div> <?php } ?> <div class="art-right"> <h2><a class="perma" href="<?php echo get_permalink(); ?>"><?php the_title();?></a></h2> <?php the_excerpt();?> </div> </div> <?php endforeach;?> <?php wp_reset_query(); ?> </div><!-- wrap-content --> </div><!-- left-content --> </div> <?php } ?> ```
Try this: ``` // All the rendered HTML $output = ''; // The posts to exclude from the random query. $exclude = []; // The remaining non-random posts $remaining = new WP_Query([ 'posts_per_page' => 7, ]); // Run the remaining query first because we have to know what should be excluded in the random query. if {$remaining->have_posts()) { while ($remaining->have_posts()) { $remaining->the_post(); // Ensure that all remainig posts are excluded from the random query. $exclude[] = get_the_ID(); ob_start(); // Render the output, consider using a function for consistency. the_title(); the_content(); // Gather and append the ouput. $output .= ob_get_clean(); } wp_reset_query(); } // Setup the random query with the excluded posts array. $random = new WP_Query([ 'posts_per_page' => 3, 'exclude' => $exclude, 'orderby' => 'rand', ]); // Run the random query if {$random->have_posts()) { while ($random->have_posts()) { $random->the_post(); ob_start(); // Again render the output, consider using a function for consistency. the_title(); the_content(); // Gather and prepend the ouput. $output = ob_get_clean() . $ouput; } wp_reset_query(); } // Display the ouput print $output; ``` You could also turn it around, first run the random query and store their ids to exclude in the remainig query what runs after the random query. You need two loops because you can't "include" 3 specific posts what are shown on top of the remaining posts. However you can try doing it with one loop what returns the posts in an incorrect order but than you use grid css to change the display order.
294,823
<p>As the title says, How can I add a custom CSS to all posts without affecting homepage CSS on WordPress?</p> <p>And I know that some plugins like "WP Add Custom CSS" would work for this and I am actually using it, and it does work but, what I want to do is give all my posts the same exact code, I don't want to give every post manually the same code over and over.</p> <p>Because if I wanted to change this code later on, then I will have to go back and edit every post that I made with this new code change.</p> <p>For example, I have this CSS code:</p> <pre><code>.post-meta { margin-right: 0px !important; } </code></pre> <p>Every post needs to have this code but without affecting homepage CSS.</p>
[ { "answer_id": 294825, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 4, "selected": true, "text": "<p>By default, WordPress sets various classes to <code>&lt;body&gt;</code> depending on which page, template, parent, .. you are on. For a single post, some of these are <code>single</code> and <code>single-post</code>, so you could use the following</p>\n\n<pre><code>body.single.single-post .post-meta {\n margin-right: 0px !important;\n}\n</code></pre>\n" }, { "answer_id": 294830, "author": "Peter HvD", "author_id": 134918, "author_profile": "https://wordpress.stackexchange.com/users/134918", "pm_score": 1, "selected": false, "text": "<p>Most themes add the class of <code>home</code> to the body element on the home page, so providing yours does you can easily target everywhere else except for the home page using the <code>:not()</code> pseudo-class.</p>\n\n<p><code>body:not(.home) .post-meta { ... }</code></p>\n\n<p>Hope that helps</p>\n" } ]
2018/02/22
[ "https://wordpress.stackexchange.com/questions/294823", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137346/" ]
As the title says, How can I add a custom CSS to all posts without affecting homepage CSS on WordPress? And I know that some plugins like "WP Add Custom CSS" would work for this and I am actually using it, and it does work but, what I want to do is give all my posts the same exact code, I don't want to give every post manually the same code over and over. Because if I wanted to change this code later on, then I will have to go back and edit every post that I made with this new code change. For example, I have this CSS code: ``` .post-meta { margin-right: 0px !important; } ``` Every post needs to have this code but without affecting homepage CSS.
By default, WordPress sets various classes to `<body>` depending on which page, template, parent, .. you are on. For a single post, some of these are `single` and `single-post`, so you could use the following ``` body.single.single-post .post-meta { margin-right: 0px !important; } ```
294,842
<p>I created a plugin which uses bootstrap datetimepicker. So i load corresponding js setting dependancies like this:</p> <pre><code>wp_enqueue_script('medapp-datetimepicker-js', $medapp_boot_timepicker_js, array( 'jquery', 'jquery-ui', 'moment', 'medapp-twitter-bootstrap-js' )); wp_enqueue_script('medapp-frontend-js', $medapp_script_js, array( 'jquery', // 'medapp-datetimepicker-js', ),'',false); </code></pre> <p>If the line commented is on, of course in my js file i can't access datetimepicker and i have the following error when i try to instanciate the datetimepicker:</p> <pre><code>TypeError: jQuery(...).datetimepicker is not a function </code></pre> <p>So i uncomment the commented line, and then load of scripts silently fails (it seems nothing is loaded after the second wp_enqueue_script, but without any console error), and the page does not display entirely.</p> <p>I know datetimepicker script is loaded correctly as i output all regegistered handlers like this:</p> <pre><code>function medapp_inspect_scripts() { global $wp_scripts; foreach( $wp_scripts-&gt;queue as $handle ) { MEDAPI::getLogger("MEDAPP")-&gt;debug( $handle ); } } </code></pre> <p>which correctly outputs the datetimepicker handler.</p> <p>Any idea how i could debug this please ?</p>
[ { "answer_id": 294844, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": false, "text": "<p>Basic JS troubleshooting - strip it down to basics. Create a new script which either has a <code>console.log('I am working')</code> or <code>alert('I am working')</code> and enqueue it without any dependencies. If it works, enqueue it with your dependencies - still with your console or alert to easily check whether it's working. If it works, now you can do a really simple function with the datepicker you really want to use in your script. Once that works, put in your more complex custom code.</p>\n\n<p>Another common thing to check - what version of jQuery does your version of Datetimepicker require, and what is loading in your version of WP? Perhaps they're not compatible.</p>\n" }, { "answer_id": 294848, "author": "Max", "author_id": 108789, "author_profile": "https://wordpress.stackexchange.com/users/108789", "pm_score": -1, "selected": false, "text": "<p>Thank you very much @WebElaine, i actually found the bug.</p>\n\n<p>It was a cascading dependancy problem:</p>\n\n<p>My datetimepicker enqueue was specifying a dependancy on moment.js, which is right, but moment was not enqueue as a script in my plugin.\nSo i enqueued moment.js as other scripts right before enqueing datetimepicker, and it works.\nI am just surprised that i was able to enqueue datetimepicker with no error raised on dependancy (maybe another plugin is already enqueuing it ?).</p>\n\n<p>Thank you very much.</p>\n" } ]
2018/02/22
[ "https://wordpress.stackexchange.com/questions/294842", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108789/" ]
I created a plugin which uses bootstrap datetimepicker. So i load corresponding js setting dependancies like this: ``` wp_enqueue_script('medapp-datetimepicker-js', $medapp_boot_timepicker_js, array( 'jquery', 'jquery-ui', 'moment', 'medapp-twitter-bootstrap-js' )); wp_enqueue_script('medapp-frontend-js', $medapp_script_js, array( 'jquery', // 'medapp-datetimepicker-js', ),'',false); ``` If the line commented is on, of course in my js file i can't access datetimepicker and i have the following error when i try to instanciate the datetimepicker: ``` TypeError: jQuery(...).datetimepicker is not a function ``` So i uncomment the commented line, and then load of scripts silently fails (it seems nothing is loaded after the second wp\_enqueue\_script, but without any console error), and the page does not display entirely. I know datetimepicker script is loaded correctly as i output all regegistered handlers like this: ``` function medapp_inspect_scripts() { global $wp_scripts; foreach( $wp_scripts->queue as $handle ) { MEDAPI::getLogger("MEDAPP")->debug( $handle ); } } ``` which correctly outputs the datetimepicker handler. Any idea how i could debug this please ?
Basic JS troubleshooting - strip it down to basics. Create a new script which either has a `console.log('I am working')` or `alert('I am working')` and enqueue it without any dependencies. If it works, enqueue it with your dependencies - still with your console or alert to easily check whether it's working. If it works, now you can do a really simple function with the datepicker you really want to use in your script. Once that works, put in your more complex custom code. Another common thing to check - what version of jQuery does your version of Datetimepicker require, and what is loading in your version of WP? Perhaps they're not compatible.
294,868
<p>I'd like to add that nice little notification bubble beside a nav item in the admin. But I don't want to slow down the whole admin by triggering a post query every time just to display the value in the little bubble. Hoping to load this one integer value into transient cache to use for display in the menu.</p> <p>Developing a custom plugin which registers a custom post type. This automatically creates the nav item in the admin, which I'd like to add the bubble to. The value within the bubble will be pulled from a simple query of how many posts (of this CPT) have been assigned to a custom taxonomy. For example if post has been assigned to custom term "pending review" then add to bubble count. </p> <p>This function here works a charm, although I have no idea how to transition to using transient cache to store and retrieve the data.... any suggestions would be greatly appreciated. Thanks!</p> <pre><code>add_action( 'admin_menu', 'add_cpt_menu_bubble' ); function add_cpt_menu_bubble() { global $menu; $count_posts = 0; // count the number of posts to show in bubble $args = array( 'order' =&gt; 'DESC', 'posts_per_page' =&gt; '-1', 'post_type' =&gt; 'custom_post_type_name', 'custom_tax_name' =&gt; 'pending-review' ); // The Query query_posts( $args ); if (have_posts()) : while ( have_posts() ) : the_post(); $count_posts++; endwhile; else: endif; wp_reset_query(); // only display the number of pending posts over a certain amount if ( $count_posts &gt; 5 ) { foreach ( $menu as $key =&gt; $value ) { if ( $menu[$key][2] == 'edit.php?post_type=custom_post_type_name' ) { $menu[$key][0] .= ' &lt;span class="update-plugins count-2"&gt;&lt;span class="update-count"&gt;' . $count_posts . '&lt;/span&gt;&lt;/span&gt;'; return; } } } } // EOF </code></pre>
[ { "answer_id": 294983, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 1, "selected": false, "text": "<p>Using your original code, I pulled the query/count/cache code to a separate function. I have not had a chance to test any of this yet so my apologies if you hit any errors. Post here if you do and I'll update when I can test it.</p>\n\n<p>Briefly, the idea is to first check for a valid transient based on its key (name) which is unique for each value and if no value exists, create it anew and store it. Either way, calling the function should return the count of <code>posttype</code> posts, up to 4 hours old. </p>\n\n<p>I randomly selected 4 hours but that is an easy parameter to edit. Simply come up with something to use in place of \"your-transient-key\" and you should be good to go.</p>\n\n<pre><code>add_action( 'admin_menu', 'add_cpt_menu_bubble' );\nfunction add_cpt_menu_bubble() {\n global $menu;\n\n // Retrieve cached value or count current number of posttype posts.\n$count_posts = wpse_count_of_posttype_posts\n\n // only display the number of pending posts over a certain amount\n if ( $count_posts &gt; 5 ) {\n foreach ( $menu as $key =&gt; $value ) {\n if ( $menu[$key][2] == 'edit.php?post_type=custom_post_type_name' ) {\n $menu[$key][0] .= ' &lt;span class=\"update-plugins count-2\"&gt;&lt;span class=\"update-count\"&gt;' . $count_posts . '&lt;/span&gt;&lt;/span&gt;';\n return;\n }\n }\n }\n\n}\n\nfunction wpse_count_of_postype_posts() {\n\n // First try to get a cached value\n if ( false === ( $num_posts = get_transient( 'your-transient-key' ) ) ) {\n // this code runs when there is no valid transient set\n\n // Your original query args\n $args = array(\n 'order' =&gt; 'DESC',\n 'posts_per_page' =&gt; '-1',\n 'post_type' =&gt; 'custom_post_type_name',\n 'custom_tax_name' =&gt; 'pending-review'\n );\n\n // Instantiate WP_Query instead\n $posttype_query = new WP_Query( $args );\n\n // One of the properties of the class is a count of the posts. No need to loop and increment a counter\n // https://codex.wordpress.org/Class_Reference/WP_Query#Properties\n $num_posts = $posttype_query-&gt;post_count;\n\n // Store the count in your transient; build it now for the future https://www.youtube.com/watch?v=XjYLvpwDNOY\n set_transient( 'your-transient-key', $num_posts, 4 * HOUR_IN_SECONDS );\n\n return $num_posts;\n }\n}\n</code></pre>\n" }, { "answer_id": 296259, "author": "Simon", "author_id": 8689, "author_profile": "https://wordpress.stackexchange.com/users/8689", "pm_score": 2, "selected": false, "text": "<p>Thanks again for the help @jdm2112. Updated a few syntax errors and used the same structure you suggested, works great!</p>\n\n<pre><code>// Add notification bubble to custom post type menu nav \nadd_action( 'admin_menu', 'add_cpt_menu_bubble' );\nfunction add_cpt_menu_bubble() {\n global $menu;\n $count_posts = tms_count_pending_posts();\n if ( $count_posts &gt; 3 ) {\n foreach ( $menu as $key =&gt; $value ) {\n if ( $menu[$key][2] == 'edit.php?post_type=custom_post_type_name' ) {\n $menu[$key][0] .= ' &lt;span class=\"update-plugins count-2\"&gt;&lt;span class=\"update-count\"&gt;' . $count_posts . '&lt;/span&gt;&lt;/span&gt;';\n return;\n }\n }\n }\n}\nfunction tms_count_pending_posts() {\n if ( false === ( $num_posts = get_transient( 'tms_pending_posts_key' ) ) ) {\n $args = array(\n 'order' =&gt; 'DESC',\n 'posts_per_page' =&gt; '-1',\n 'post_type' =&gt; 'custom_post_type_name',\n 'custom_tax' =&gt; 'pending-review'\n );\n $posttype_query = new WP_Query( $args );\n ($posttype_query-&gt;post_count) ? $num_posts = $posttype_query-&gt;post_count : $num_posts = 0;\n set_transient( 'tms_pending_posts_key', $num_posts, 30 ); \n } \n return $num_posts;\n}\n</code></pre>\n" } ]
2018/02/22
[ "https://wordpress.stackexchange.com/questions/294868", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8689/" ]
I'd like to add that nice little notification bubble beside a nav item in the admin. But I don't want to slow down the whole admin by triggering a post query every time just to display the value in the little bubble. Hoping to load this one integer value into transient cache to use for display in the menu. Developing a custom plugin which registers a custom post type. This automatically creates the nav item in the admin, which I'd like to add the bubble to. The value within the bubble will be pulled from a simple query of how many posts (of this CPT) have been assigned to a custom taxonomy. For example if post has been assigned to custom term "pending review" then add to bubble count. This function here works a charm, although I have no idea how to transition to using transient cache to store and retrieve the data.... any suggestions would be greatly appreciated. Thanks! ``` add_action( 'admin_menu', 'add_cpt_menu_bubble' ); function add_cpt_menu_bubble() { global $menu; $count_posts = 0; // count the number of posts to show in bubble $args = array( 'order' => 'DESC', 'posts_per_page' => '-1', 'post_type' => 'custom_post_type_name', 'custom_tax_name' => 'pending-review' ); // The Query query_posts( $args ); if (have_posts()) : while ( have_posts() ) : the_post(); $count_posts++; endwhile; else: endif; wp_reset_query(); // only display the number of pending posts over a certain amount if ( $count_posts > 5 ) { foreach ( $menu as $key => $value ) { if ( $menu[$key][2] == 'edit.php?post_type=custom_post_type_name' ) { $menu[$key][0] .= ' <span class="update-plugins count-2"><span class="update-count">' . $count_posts . '</span></span>'; return; } } } } // EOF ```
Thanks again for the help @jdm2112. Updated a few syntax errors and used the same structure you suggested, works great! ``` // Add notification bubble to custom post type menu nav add_action( 'admin_menu', 'add_cpt_menu_bubble' ); function add_cpt_menu_bubble() { global $menu; $count_posts = tms_count_pending_posts(); if ( $count_posts > 3 ) { foreach ( $menu as $key => $value ) { if ( $menu[$key][2] == 'edit.php?post_type=custom_post_type_name' ) { $menu[$key][0] .= ' <span class="update-plugins count-2"><span class="update-count">' . $count_posts . '</span></span>'; return; } } } } function tms_count_pending_posts() { if ( false === ( $num_posts = get_transient( 'tms_pending_posts_key' ) ) ) { $args = array( 'order' => 'DESC', 'posts_per_page' => '-1', 'post_type' => 'custom_post_type_name', 'custom_tax' => 'pending-review' ); $posttype_query = new WP_Query( $args ); ($posttype_query->post_count) ? $num_posts = $posttype_query->post_count : $num_posts = 0; set_transient( 'tms_pending_posts_key', $num_posts, 30 ); } return $num_posts; } ```
294,880
<p>How do I display a different group of photos with each blog post without uploading the photos to the Wordpress Media Library?</p> <p>I’m using Wordpress for my blog. The blog is sort of a diary. One blog per day. The post title is each day’s date, in the format yyyymmdd. For each blog post, I take 10-50 photos. All the photos are in a single folder on my server. Each photo is numbered sequentially (1 thru whatever) &amp; the file name of each image is the date (yyyymmdd) concatenated with the numeric counter. </p> <p>I rather not upload all these photos into the Wordpress Media Library. (Or maybe I would upload just one photo per post.) When a visitor clicks on a link to view a post (of a particular day), I would like each photo to be displayed at the end of the post content. Either in a carousel or a grid. </p> <p>I know that this is pretty straightforward if I would upload the photos into the WP Media Library, but that is what I’m trying to avoid. </p> <p>I have at least 3 theories:</p> <ol> <li>figure out how to enter (programmatically) the image info to the media library. (Not sure if this can be done without triggering the photos being upload to the media library, which I don't want)</li> <li>do an add_filter on the_content (to insert the html needed),</li> <li>use a hook to capture output buffer &amp; insert the html.</li> </ol>
[ { "answer_id": 294983, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 1, "selected": false, "text": "<p>Using your original code, I pulled the query/count/cache code to a separate function. I have not had a chance to test any of this yet so my apologies if you hit any errors. Post here if you do and I'll update when I can test it.</p>\n\n<p>Briefly, the idea is to first check for a valid transient based on its key (name) which is unique for each value and if no value exists, create it anew and store it. Either way, calling the function should return the count of <code>posttype</code> posts, up to 4 hours old. </p>\n\n<p>I randomly selected 4 hours but that is an easy parameter to edit. Simply come up with something to use in place of \"your-transient-key\" and you should be good to go.</p>\n\n<pre><code>add_action( 'admin_menu', 'add_cpt_menu_bubble' );\nfunction add_cpt_menu_bubble() {\n global $menu;\n\n // Retrieve cached value or count current number of posttype posts.\n$count_posts = wpse_count_of_posttype_posts\n\n // only display the number of pending posts over a certain amount\n if ( $count_posts &gt; 5 ) {\n foreach ( $menu as $key =&gt; $value ) {\n if ( $menu[$key][2] == 'edit.php?post_type=custom_post_type_name' ) {\n $menu[$key][0] .= ' &lt;span class=\"update-plugins count-2\"&gt;&lt;span class=\"update-count\"&gt;' . $count_posts . '&lt;/span&gt;&lt;/span&gt;';\n return;\n }\n }\n }\n\n}\n\nfunction wpse_count_of_postype_posts() {\n\n // First try to get a cached value\n if ( false === ( $num_posts = get_transient( 'your-transient-key' ) ) ) {\n // this code runs when there is no valid transient set\n\n // Your original query args\n $args = array(\n 'order' =&gt; 'DESC',\n 'posts_per_page' =&gt; '-1',\n 'post_type' =&gt; 'custom_post_type_name',\n 'custom_tax_name' =&gt; 'pending-review'\n );\n\n // Instantiate WP_Query instead\n $posttype_query = new WP_Query( $args );\n\n // One of the properties of the class is a count of the posts. No need to loop and increment a counter\n // https://codex.wordpress.org/Class_Reference/WP_Query#Properties\n $num_posts = $posttype_query-&gt;post_count;\n\n // Store the count in your transient; build it now for the future https://www.youtube.com/watch?v=XjYLvpwDNOY\n set_transient( 'your-transient-key', $num_posts, 4 * HOUR_IN_SECONDS );\n\n return $num_posts;\n }\n}\n</code></pre>\n" }, { "answer_id": 296259, "author": "Simon", "author_id": 8689, "author_profile": "https://wordpress.stackexchange.com/users/8689", "pm_score": 2, "selected": false, "text": "<p>Thanks again for the help @jdm2112. Updated a few syntax errors and used the same structure you suggested, works great!</p>\n\n<pre><code>// Add notification bubble to custom post type menu nav \nadd_action( 'admin_menu', 'add_cpt_menu_bubble' );\nfunction add_cpt_menu_bubble() {\n global $menu;\n $count_posts = tms_count_pending_posts();\n if ( $count_posts &gt; 3 ) {\n foreach ( $menu as $key =&gt; $value ) {\n if ( $menu[$key][2] == 'edit.php?post_type=custom_post_type_name' ) {\n $menu[$key][0] .= ' &lt;span class=\"update-plugins count-2\"&gt;&lt;span class=\"update-count\"&gt;' . $count_posts . '&lt;/span&gt;&lt;/span&gt;';\n return;\n }\n }\n }\n}\nfunction tms_count_pending_posts() {\n if ( false === ( $num_posts = get_transient( 'tms_pending_posts_key' ) ) ) {\n $args = array(\n 'order' =&gt; 'DESC',\n 'posts_per_page' =&gt; '-1',\n 'post_type' =&gt; 'custom_post_type_name',\n 'custom_tax' =&gt; 'pending-review'\n );\n $posttype_query = new WP_Query( $args );\n ($posttype_query-&gt;post_count) ? $num_posts = $posttype_query-&gt;post_count : $num_posts = 0;\n set_transient( 'tms_pending_posts_key', $num_posts, 30 ); \n } \n return $num_posts;\n}\n</code></pre>\n" } ]
2018/02/22
[ "https://wordpress.stackexchange.com/questions/294880", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137390/" ]
How do I display a different group of photos with each blog post without uploading the photos to the Wordpress Media Library? I’m using Wordpress for my blog. The blog is sort of a diary. One blog per day. The post title is each day’s date, in the format yyyymmdd. For each blog post, I take 10-50 photos. All the photos are in a single folder on my server. Each photo is numbered sequentially (1 thru whatever) & the file name of each image is the date (yyyymmdd) concatenated with the numeric counter. I rather not upload all these photos into the Wordpress Media Library. (Or maybe I would upload just one photo per post.) When a visitor clicks on a link to view a post (of a particular day), I would like each photo to be displayed at the end of the post content. Either in a carousel or a grid. I know that this is pretty straightforward if I would upload the photos into the WP Media Library, but that is what I’m trying to avoid. I have at least 3 theories: 1. figure out how to enter (programmatically) the image info to the media library. (Not sure if this can be done without triggering the photos being upload to the media library, which I don't want) 2. do an add\_filter on the\_content (to insert the html needed), 3. use a hook to capture output buffer & insert the html.
Thanks again for the help @jdm2112. Updated a few syntax errors and used the same structure you suggested, works great! ``` // Add notification bubble to custom post type menu nav add_action( 'admin_menu', 'add_cpt_menu_bubble' ); function add_cpt_menu_bubble() { global $menu; $count_posts = tms_count_pending_posts(); if ( $count_posts > 3 ) { foreach ( $menu as $key => $value ) { if ( $menu[$key][2] == 'edit.php?post_type=custom_post_type_name' ) { $menu[$key][0] .= ' <span class="update-plugins count-2"><span class="update-count">' . $count_posts . '</span></span>'; return; } } } } function tms_count_pending_posts() { if ( false === ( $num_posts = get_transient( 'tms_pending_posts_key' ) ) ) { $args = array( 'order' => 'DESC', 'posts_per_page' => '-1', 'post_type' => 'custom_post_type_name', 'custom_tax' => 'pending-review' ); $posttype_query = new WP_Query( $args ); ($posttype_query->post_count) ? $num_posts = $posttype_query->post_count : $num_posts = 0; set_transient( 'tms_pending_posts_key', $num_posts, 30 ); } return $num_posts; } ```
294,907
<p>Currently, I can only get the post by user roles on specific sites. What I need is to have a query that will get the post from user role on other site.</p> <pre><code>Example Users: Site A - user(admin site a, editor site a) Site B - user(editor site b) Site C - user(editor site c) </code></pre> <blockquote> <p>Site A - index list of posts</p> <ul> <li>Post by admin site A</li> <li>Post by editor site A</li> </ul> <p>Site B - index list of posts</p> <ul> <li>post by admin site A</li> <li>post by editor Site B.</li> </ul> <p>Site C - index list of posts</p> <ul> <li>post by admin site A</li> <li>post by editor Site C.</li> </ul> </blockquote>
[ { "answer_id": 294908, "author": "Mohit Kumar", "author_id": 111870, "author_profile": "https://wordpress.stackexchange.com/users/111870", "pm_score": -1, "selected": false, "text": "<p>As per your questions, I think you want to call separate php file (my-plugin.php) on plugin menu click. If i am right you can follow code below otherwise sorry for that.</p>\n\n<p>you can call this through callback function.</p>\n\n<pre><code>add_action('admin_menu', 'my_plugin_menu');\n\nfunction my_plugin_menu() {\n add_options_page(\n 'My Plugin Options'\n , 'My Plugin'\n , 'manage_options'\n , 'my-unique-identifier'\n , 'my_plugin_options'\n );\n}\n\nfunction my_plugin_options() {\n require 'my-plugin.php';\n}\n</code></pre>\n" }, { "answer_id": 294912, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": true, "text": "<p>Generaly no, or at least if you work hard enough to make it happen it will make much more sense to just use <code>mydomain.com/wp-admin/my-plugin</code> (without the php extension).</p>\n\n<p>The reason is that by default the htaccess rules wordpress uses, first try to locate a file in the implied path, and if it is not there it \"fires\" the front end processing, something you most likely do not want to happen in the context of admin session. Therefor urls under <code>wp-admin</code> should map to actual PHP files at the implied location.</p>\n\n<p>How to get around this limitation? There are two parts with the easiest one is modifying the htaccess to map the url you want for your admin page into the \"normal\" wordpress admin url, or intercept the URL very early in the processing of the request and modify the relevant PHP globals appropriately. The harder one will be to modify the output of the relevant admin APIs to generate the right URL in the relevant contexts and there might be always some additional unexpected edge cases that you will need to handle.</p>\n" } ]
2018/02/23
[ "https://wordpress.stackexchange.com/questions/294907", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137408/" ]
Currently, I can only get the post by user roles on specific sites. What I need is to have a query that will get the post from user role on other site. ``` Example Users: Site A - user(admin site a, editor site a) Site B - user(editor site b) Site C - user(editor site c) ``` > > Site A - index list of posts > > > * Post by admin site A > * Post by editor site A > > > Site B - index list of posts > > > * post by admin site A > * post by editor Site B. > > > Site C - index list of posts > > > * post by admin site A > * post by editor Site C. > > >
Generaly no, or at least if you work hard enough to make it happen it will make much more sense to just use `mydomain.com/wp-admin/my-plugin` (without the php extension). The reason is that by default the htaccess rules wordpress uses, first try to locate a file in the implied path, and if it is not there it "fires" the front end processing, something you most likely do not want to happen in the context of admin session. Therefor urls under `wp-admin` should map to actual PHP files at the implied location. How to get around this limitation? There are two parts with the easiest one is modifying the htaccess to map the url you want for your admin page into the "normal" wordpress admin url, or intercept the URL very early in the processing of the request and modify the relevant PHP globals appropriately. The harder one will be to modify the output of the relevant admin APIs to generate the right URL in the relevant contexts and there might be always some additional unexpected edge cases that you will need to handle.
294,922
<p>I am using the auto_core_update_email hook to modify the auto update email sent by WordPress. However I cannot figure out how to add line breaks to the email body. Here's my code:</p> <pre><code>function example_filter_auto_update_email($email) { $email['to'] = array('[email protected]', '[email protected]'); $email['subject'] = 'Auto Update'; $email['body'] = 'Hello,%0D%0A' . 'Lorem ipsum.%0D%0A' . 'Many thanks,%0D%0A' . 'WordPress'; return $email; } add_filter('auto_core_update_email', 'example_filter_auto_update_email', 1); </code></pre> <p>I have also tried using: <code>&lt;br /&gt;</code>, <code>\r\n</code>, as well as <code>%0D%0A</code>, seen above. However, in each case the string is just printed in my email client like this: </p> <p>Hello%0D%0ALorem Ipsum%0D%0AMany thanks%0D%0AWordPress</p> <p>How can I get line breaks printed in my auto update emails? If it helps the emails are being sent by SMTP. </p> <p>Thanks a lot!</p>
[ { "answer_id": 294908, "author": "Mohit Kumar", "author_id": 111870, "author_profile": "https://wordpress.stackexchange.com/users/111870", "pm_score": -1, "selected": false, "text": "<p>As per your questions, I think you want to call separate php file (my-plugin.php) on plugin menu click. If i am right you can follow code below otherwise sorry for that.</p>\n\n<p>you can call this through callback function.</p>\n\n<pre><code>add_action('admin_menu', 'my_plugin_menu');\n\nfunction my_plugin_menu() {\n add_options_page(\n 'My Plugin Options'\n , 'My Plugin'\n , 'manage_options'\n , 'my-unique-identifier'\n , 'my_plugin_options'\n );\n}\n\nfunction my_plugin_options() {\n require 'my-plugin.php';\n}\n</code></pre>\n" }, { "answer_id": 294912, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": true, "text": "<p>Generaly no, or at least if you work hard enough to make it happen it will make much more sense to just use <code>mydomain.com/wp-admin/my-plugin</code> (without the php extension).</p>\n\n<p>The reason is that by default the htaccess rules wordpress uses, first try to locate a file in the implied path, and if it is not there it \"fires\" the front end processing, something you most likely do not want to happen in the context of admin session. Therefor urls under <code>wp-admin</code> should map to actual PHP files at the implied location.</p>\n\n<p>How to get around this limitation? There are two parts with the easiest one is modifying the htaccess to map the url you want for your admin page into the \"normal\" wordpress admin url, or intercept the URL very early in the processing of the request and modify the relevant PHP globals appropriately. The harder one will be to modify the output of the relevant admin APIs to generate the right URL in the relevant contexts and there might be always some additional unexpected edge cases that you will need to handle.</p>\n" } ]
2018/02/23
[ "https://wordpress.stackexchange.com/questions/294922", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135943/" ]
I am using the auto\_core\_update\_email hook to modify the auto update email sent by WordPress. However I cannot figure out how to add line breaks to the email body. Here's my code: ``` function example_filter_auto_update_email($email) { $email['to'] = array('[email protected]', '[email protected]'); $email['subject'] = 'Auto Update'; $email['body'] = 'Hello,%0D%0A' . 'Lorem ipsum.%0D%0A' . 'Many thanks,%0D%0A' . 'WordPress'; return $email; } add_filter('auto_core_update_email', 'example_filter_auto_update_email', 1); ``` I have also tried using: `<br />`, `\r\n`, as well as `%0D%0A`, seen above. However, in each case the string is just printed in my email client like this: Hello%0D%0ALorem Ipsum%0D%0AMany thanks%0D%0AWordPress How can I get line breaks printed in my auto update emails? If it helps the emails are being sent by SMTP. Thanks a lot!
Generaly no, or at least if you work hard enough to make it happen it will make much more sense to just use `mydomain.com/wp-admin/my-plugin` (without the php extension). The reason is that by default the htaccess rules wordpress uses, first try to locate a file in the implied path, and if it is not there it "fires" the front end processing, something you most likely do not want to happen in the context of admin session. Therefor urls under `wp-admin` should map to actual PHP files at the implied location. How to get around this limitation? There are two parts with the easiest one is modifying the htaccess to map the url you want for your admin page into the "normal" wordpress admin url, or intercept the URL very early in the processing of the request and modify the relevant PHP globals appropriately. The harder one will be to modify the output of the relevant admin APIs to generate the right URL in the relevant contexts and there might be always some additional unexpected edge cases that you will need to handle.
294,946
<p>I synchronize some data of my plugin with an extern API. This synchronize-process should fire every minute. So I use the following code to do that:</p> <pre><code>if ( ! get_transient( 'my_task_sync_method' ) ) { set_transient( 'my_task_sync_method', true, 1 * MINUTE_IN_SECONDS ); my_task_sync_method(); } </code></pre> <p>Currently I run this Code within my plugin initial code. I know this is a workaround and not the normal use case for transient, but it is the best solution I found so far.</p> <p>This works fine, but sometimes when I reload a backend page (e.g. the dashboard) I'm getting some parts of a custom post admin page, which i have generated. It seems to happen when I reload the page on the time my sync-process is running. It's quite difficult to adjust this incident. But mabye some one know this kind of problem and is able to help me? If there is a better solution to do a synchronization I would be happy if you tell me the better way.</p>
[ { "answer_id": 294966, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 3, "selected": true, "text": "<p>To my understanding, <code>*_transient()</code> is basically <code>*_option()</code> wrapped in a cache-timer.</p>\n\n<p>What that means in this context, is that <code>set_transient( '...', true, * MINUTE_IN_SECONDS );</code> will <strong>not</strong> run/re-evaluate every minute. Instead it will run/re-evaluate when the page has loaded by a visitor/user, and the data therein is older than 60 seconds. This is not ideal because what it does is puts the processing of the sync method onto the users load time, which isn't good, and can mess up, like the hiccup your experiencing - it correlates with this:</p>\n\n<blockquote>\n <p>It seems to happen when I reload the page on the time my sync-process is running</p>\n</blockquote>\n\n<p>So your visiting the admin after >60 seconds of no other visits to the site. The <code>_transient</code> is thus expired, and fires your <code>my_task_sync_method()</code> on your page load, which must be echo'ing or interrupting your load processes in some way.</p>\n\n<hr>\n\n<p>To resolve this, first, you should use <a href=\"https://developer.wordpress.org/plugins/cron/\" rel=\"nofollow noreferrer\">Wordpress Cron</a>, not <code>_transient</code>. Cron jobs run in the background, and adhere to the 60-second sync, without relying on users visiting. </p>\n\n<p>Here's a base snippet for a cron task:</p>\n\n<pre><code>// add a 60 second cron schedule\nadd_filter('cron_schedules', function ( $schedules ) {\n $schedules['everyminute'] = array(\n 'interval' =&gt; 60,\n 'display' =&gt; __('Every Minute')\n );\n return $schedules;\n});\n\n// register your cronjob\nadd_action('wp', function () {\n if ( !wp_next_scheduled( 'my_task_sync_cronjob' ) )\n wp_schedule_event(time(), 'everyminute', 'my_task_sync_cronjob');\n});\n\n// the registered cron hook, that'll fire your function\nadd_action('my_task_sync_cronjob', 'my_task_sync_method');\n</code></pre>\n\n<p>Secondly, you should ensure <code>my_task_sync_method()</code> isn't echo'ing any data. I am assuming it does given your symptoms.</p>\n\n<hr>\n\n<p><em>Please note I've placed the functions in the hooks anonymously, I did this for easier display here. You may want to make them callbacks instead incase other developers want to tap into your hooks.</em></p>\n" }, { "answer_id": 294971, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Your synchronization function probably tries to do too much especially if you need to contact external resources. </p>\n\n<p>The proper way to do it is to fetch the information when it is <strong>more than a minute stale</strong> instead of every minute. This way you are sure to not end up in limbo if a sync failed.</p>\n\n<p>I personally hate transients as they are <strong>by design</strong> not reliable. You should use an option in which you store the next time an update should be made and check if that time had passed, with maybe an additional \"flag\" stored in the option that indicates when an update is on the way to prevent double updates.</p>\n\n<p>Additional note: While 1 minute interval should be OK most of the time, my gut feeling is that it is too short. Web servers and web software were not designed to be very accurate about their timings, and the situation in which you site can not have information which is more than one minute stale sounds ridiculous. Assuming you are doing some additional DB writes on each sync, you are taxing your server abilities for something that might not actually be needed.</p>\n" } ]
2018/02/23
[ "https://wordpress.stackexchange.com/questions/294946", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80958/" ]
I synchronize some data of my plugin with an extern API. This synchronize-process should fire every minute. So I use the following code to do that: ``` if ( ! get_transient( 'my_task_sync_method' ) ) { set_transient( 'my_task_sync_method', true, 1 * MINUTE_IN_SECONDS ); my_task_sync_method(); } ``` Currently I run this Code within my plugin initial code. I know this is a workaround and not the normal use case for transient, but it is the best solution I found so far. This works fine, but sometimes when I reload a backend page (e.g. the dashboard) I'm getting some parts of a custom post admin page, which i have generated. It seems to happen when I reload the page on the time my sync-process is running. It's quite difficult to adjust this incident. But mabye some one know this kind of problem and is able to help me? If there is a better solution to do a synchronization I would be happy if you tell me the better way.
To my understanding, `*_transient()` is basically `*_option()` wrapped in a cache-timer. What that means in this context, is that `set_transient( '...', true, * MINUTE_IN_SECONDS );` will **not** run/re-evaluate every minute. Instead it will run/re-evaluate when the page has loaded by a visitor/user, and the data therein is older than 60 seconds. This is not ideal because what it does is puts the processing of the sync method onto the users load time, which isn't good, and can mess up, like the hiccup your experiencing - it correlates with this: > > It seems to happen when I reload the page on the time my sync-process is running > > > So your visiting the admin after >60 seconds of no other visits to the site. The `_transient` is thus expired, and fires your `my_task_sync_method()` on your page load, which must be echo'ing or interrupting your load processes in some way. --- To resolve this, first, you should use [Wordpress Cron](https://developer.wordpress.org/plugins/cron/), not `_transient`. Cron jobs run in the background, and adhere to the 60-second sync, without relying on users visiting. Here's a base snippet for a cron task: ``` // add a 60 second cron schedule add_filter('cron_schedules', function ( $schedules ) { $schedules['everyminute'] = array( 'interval' => 60, 'display' => __('Every Minute') ); return $schedules; }); // register your cronjob add_action('wp', function () { if ( !wp_next_scheduled( 'my_task_sync_cronjob' ) ) wp_schedule_event(time(), 'everyminute', 'my_task_sync_cronjob'); }); // the registered cron hook, that'll fire your function add_action('my_task_sync_cronjob', 'my_task_sync_method'); ``` Secondly, you should ensure `my_task_sync_method()` isn't echo'ing any data. I am assuming it does given your symptoms. --- *Please note I've placed the functions in the hooks anonymously, I did this for easier display here. You may want to make them callbacks instead incase other developers want to tap into your hooks.*
294,975
<p>It is in Wordpress, Divi. It seemed to me a simple task but somehow I haven't managed to get the proper result spending tons of hours with coding and testing. Currently I'm working on a website, where there are posts and I intend to give the possibility the user to jump to the adjacent posts with a simple link pointing to them. I've tried to put them in <code>functions.php</code>, then in <code>single.php</code> but the same result... Nothing. I checked it via Wordpress <code>debug.log</code>, it shows that the functions return no value at all. Note that I mention <code>debug.log</code>, because I forwarded outputs over there.</p> <pre><code>add_filter( 'the_content', 'post_navigation', 10, 2 ); function post_navigation($content) { $post = get_post(); $post_type = get_post_type( $post ); if ( $post_type == 'post' ) { $next_p = get_previous_posts_link(); $content = $content . $next_p; return $content; } else { return $content; } } </code></pre> <p>It has no proper formatted output, but first I just wanted to get any result. Note: <code>debug.log</code> shows that the the_content hook has been 2 times called at a simple post displaying second times with the content: </p> <pre><code>You are being timed-out out due to inactivity. Please choose to stay signed in or to logoff.&lt;/p&gt; &lt;p&gt;Otherwise, you will be logged off automatically.&lt;/p&gt; </code></pre> <p>Any help would be highly appriciated!</p>
[ { "answer_id": 294977, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 3, "selected": true, "text": "<p><strong>Warning Edit</strong>: Mark Kaplun's answer brings up a very good point - this will modify your content in unexpected ways. Say, for instance, you have another application that reads this post content from the WordPress API - that content will also have these links which is probably not what you want. You should really be applying these methods in your <strong>theme templates</strong> instead of appending this information to the content itself. You could possibly use sanity checks such as checking against the <code>global $pagenow</code> variable, or other methods, to ensure you only do this operation when you're viewing a post on the front-end. </p>\n\n<p>It appears you're using the incorrect methods. WordPress is kind of tricky sometimes, and in this case you want to be using <code>get_previous_post_link</code> instead of <code>get_previous_posts_link</code> (<strong>note</strong>: the difference is that in the method you are calling, <em>posts</em> is plural - in the method you want, <em>post</em> is singular).</p>\n\n<p>So give these a shot</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/previous_post_link\" rel=\"nofollow noreferrer\">get_previous_post_link</a> - <em>Retrieves the previous post link that is adjacent to the current post.</em></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/get_next_post_link/\" rel=\"nofollow noreferrer\">get_next_post_link</a> - <em>Retrieves the next post link that is adjacent to the current post.</em></li>\n</ul>\n\n<p><strong>EDIT</strong>: Here is an updated example based on your code</p>\n\n<pre><code>add_filter( 'the_content', 'post_navigation', 10, 2 );\n\nfunction post_navigation($content) {\n $post = get_post();\n\n if ( 'post' === $post-&gt;post_type ) {\n $next_p = get_next_post_link();\n $prev_p = get_previous_post_link();\n $content = \"{$content}&lt;br/&gt;{$prev_p} | {$next_p}\";\n }\n\n return $content; \n}\n</code></pre>\n" }, { "answer_id": 294980, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>Just don't do it. The <code>the_content</code> filter supposed to automatically amend the content, while what you are trying to do is to add a decoration, not a content. You are going to hurt in very unexpected ways depending on where exactly you set the filter and how well you remove it after your intended use. (for example, place it in a global scope and your excerpts might get the links)</p>\n\n<p>If you have to manipulate the content being displayed by adding a decoration to it, do it in the theme, no other place.</p>\n" } ]
2018/02/23
[ "https://wordpress.stackexchange.com/questions/294975", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137445/" ]
It is in Wordpress, Divi. It seemed to me a simple task but somehow I haven't managed to get the proper result spending tons of hours with coding and testing. Currently I'm working on a website, where there are posts and I intend to give the possibility the user to jump to the adjacent posts with a simple link pointing to them. I've tried to put them in `functions.php`, then in `single.php` but the same result... Nothing. I checked it via Wordpress `debug.log`, it shows that the functions return no value at all. Note that I mention `debug.log`, because I forwarded outputs over there. ``` add_filter( 'the_content', 'post_navigation', 10, 2 ); function post_navigation($content) { $post = get_post(); $post_type = get_post_type( $post ); if ( $post_type == 'post' ) { $next_p = get_previous_posts_link(); $content = $content . $next_p; return $content; } else { return $content; } } ``` It has no proper formatted output, but first I just wanted to get any result. Note: `debug.log` shows that the the\_content hook has been 2 times called at a simple post displaying second times with the content: ``` You are being timed-out out due to inactivity. Please choose to stay signed in or to logoff.</p> <p>Otherwise, you will be logged off automatically.</p> ``` Any help would be highly appriciated!
**Warning Edit**: Mark Kaplun's answer brings up a very good point - this will modify your content in unexpected ways. Say, for instance, you have another application that reads this post content from the WordPress API - that content will also have these links which is probably not what you want. You should really be applying these methods in your **theme templates** instead of appending this information to the content itself. You could possibly use sanity checks such as checking against the `global $pagenow` variable, or other methods, to ensure you only do this operation when you're viewing a post on the front-end. It appears you're using the incorrect methods. WordPress is kind of tricky sometimes, and in this case you want to be using `get_previous_post_link` instead of `get_previous_posts_link` (**note**: the difference is that in the method you are calling, *posts* is plural - in the method you want, *post* is singular). So give these a shot * [get\_previous\_post\_link](https://codex.wordpress.org/Function_Reference/previous_post_link) - *Retrieves the previous post link that is adjacent to the current post.* * [get\_next\_post\_link](https://developer.wordpress.org/reference/functions/get_next_post_link/) - *Retrieves the next post link that is adjacent to the current post.* **EDIT**: Here is an updated example based on your code ``` add_filter( 'the_content', 'post_navigation', 10, 2 ); function post_navigation($content) { $post = get_post(); if ( 'post' === $post->post_type ) { $next_p = get_next_post_link(); $prev_p = get_previous_post_link(); $content = "{$content}<br/>{$prev_p} | {$next_p}"; } return $content; } ```
295,022
<p>I have created custom post type and created the post in a front custom form using logged in user and set status 'pending'. Now I want to show my created post preview like the published post.</p> <p>I have hit URL like admin <a href="http://localhost/project/?post_type=deals&amp;p=3305" rel="nofollow noreferrer">http://localhost/project/?post_type=deals&amp;p=3305</a></p> <p>but it is working for admin, not for author user.</p> <p>In Another way, we can say that how to show pending custom post for the author only for preview.</p> <p>my code--->></p> <pre><code>'public' =&gt; true,'publicly_queryable' =&gt; true,'show_ui' =&gt; true, </code></pre> <p>Please help</p>
[ { "answer_id": 294977, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 3, "selected": true, "text": "<p><strong>Warning Edit</strong>: Mark Kaplun's answer brings up a very good point - this will modify your content in unexpected ways. Say, for instance, you have another application that reads this post content from the WordPress API - that content will also have these links which is probably not what you want. You should really be applying these methods in your <strong>theme templates</strong> instead of appending this information to the content itself. You could possibly use sanity checks such as checking against the <code>global $pagenow</code> variable, or other methods, to ensure you only do this operation when you're viewing a post on the front-end. </p>\n\n<p>It appears you're using the incorrect methods. WordPress is kind of tricky sometimes, and in this case you want to be using <code>get_previous_post_link</code> instead of <code>get_previous_posts_link</code> (<strong>note</strong>: the difference is that in the method you are calling, <em>posts</em> is plural - in the method you want, <em>post</em> is singular).</p>\n\n<p>So give these a shot</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/previous_post_link\" rel=\"nofollow noreferrer\">get_previous_post_link</a> - <em>Retrieves the previous post link that is adjacent to the current post.</em></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/get_next_post_link/\" rel=\"nofollow noreferrer\">get_next_post_link</a> - <em>Retrieves the next post link that is adjacent to the current post.</em></li>\n</ul>\n\n<p><strong>EDIT</strong>: Here is an updated example based on your code</p>\n\n<pre><code>add_filter( 'the_content', 'post_navigation', 10, 2 );\n\nfunction post_navigation($content) {\n $post = get_post();\n\n if ( 'post' === $post-&gt;post_type ) {\n $next_p = get_next_post_link();\n $prev_p = get_previous_post_link();\n $content = \"{$content}&lt;br/&gt;{$prev_p} | {$next_p}\";\n }\n\n return $content; \n}\n</code></pre>\n" }, { "answer_id": 294980, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>Just don't do it. The <code>the_content</code> filter supposed to automatically amend the content, while what you are trying to do is to add a decoration, not a content. You are going to hurt in very unexpected ways depending on where exactly you set the filter and how well you remove it after your intended use. (for example, place it in a global scope and your excerpts might get the links)</p>\n\n<p>If you have to manipulate the content being displayed by adding a decoration to it, do it in the theme, no other place.</p>\n" } ]
2018/02/24
[ "https://wordpress.stackexchange.com/questions/295022", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137451/" ]
I have created custom post type and created the post in a front custom form using logged in user and set status 'pending'. Now I want to show my created post preview like the published post. I have hit URL like admin <http://localhost/project/?post_type=deals&p=3305> but it is working for admin, not for author user. In Another way, we can say that how to show pending custom post for the author only for preview. my code--->> ``` 'public' => true,'publicly_queryable' => true,'show_ui' => true, ``` Please help
**Warning Edit**: Mark Kaplun's answer brings up a very good point - this will modify your content in unexpected ways. Say, for instance, you have another application that reads this post content from the WordPress API - that content will also have these links which is probably not what you want. You should really be applying these methods in your **theme templates** instead of appending this information to the content itself. You could possibly use sanity checks such as checking against the `global $pagenow` variable, or other methods, to ensure you only do this operation when you're viewing a post on the front-end. It appears you're using the incorrect methods. WordPress is kind of tricky sometimes, and in this case you want to be using `get_previous_post_link` instead of `get_previous_posts_link` (**note**: the difference is that in the method you are calling, *posts* is plural - in the method you want, *post* is singular). So give these a shot * [get\_previous\_post\_link](https://codex.wordpress.org/Function_Reference/previous_post_link) - *Retrieves the previous post link that is adjacent to the current post.* * [get\_next\_post\_link](https://developer.wordpress.org/reference/functions/get_next_post_link/) - *Retrieves the next post link that is adjacent to the current post.* **EDIT**: Here is an updated example based on your code ``` add_filter( 'the_content', 'post_navigation', 10, 2 ); function post_navigation($content) { $post = get_post(); if ( 'post' === $post->post_type ) { $next_p = get_next_post_link(); $prev_p = get_previous_post_link(); $content = "{$content}<br/>{$prev_p} | {$next_p}"; } return $content; } ```
295,043
<p>If I enqueue styles from my plugin, then it loads after theme's styles. That's why some CSS of my plugin is overriding by theme's CSS. This problem would be fixed if I can ensure my plugin's styles load after theme's styles.</p>
[ { "answer_id": 295046, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>No. (or technically there might be, but in a few days there will be a question here about how to enqueue theme styles before plugin styles).</p>\n\n<p>If your styles are getting overridden by theme styles it means that you do not properly prefix your classes.</p>\n" }, { "answer_id": 295050, "author": "obiPlabon", "author_id": 135737, "author_profile": "https://wordpress.stackexchange.com/users/135737", "pm_score": 3, "selected": true, "text": "<p>It's easy to add your plugin stylesheet after theme stylesheet. If you're sure that your theme styles and plugin styles have the same selector weight (<em>theme has this style <code>.site-header { background-color: #ccc; }</code> and your plugin has this <code>.site-header { background-color: #f1f1f1; }</code></em>) then enqueuing plugin stylesheet after theme stylesheet will work.</p>\n\n<p>If you're enqueuing with <code>wp_enqueue_scripts</code> action hook then changing the hook priority parameter will do the work. Here's an example:</p>\n\n<pre><code>function op_enqueue_scripts() {\n wp_enqueue_style( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' );\n}\nadd_action( 'wp_enqueue_scripts', 'op_enqueue_scripts', 50 );\n</code></pre>\n\n<p>If priority 50 doesn't work then try increasing that to 80 or 100.</p>\n" } ]
2018/02/24
[ "https://wordpress.stackexchange.com/questions/295043", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75264/" ]
If I enqueue styles from my plugin, then it loads after theme's styles. That's why some CSS of my plugin is overriding by theme's CSS. This problem would be fixed if I can ensure my plugin's styles load after theme's styles.
It's easy to add your plugin stylesheet after theme stylesheet. If you're sure that your theme styles and plugin styles have the same selector weight (*theme has this style `.site-header { background-color: #ccc; }` and your plugin has this `.site-header { background-color: #f1f1f1; }`*) then enqueuing plugin stylesheet after theme stylesheet will work. If you're enqueuing with `wp_enqueue_scripts` action hook then changing the hook priority parameter will do the work. Here's an example: ``` function op_enqueue_scripts() { wp_enqueue_style( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' ); } add_action( 'wp_enqueue_scripts', 'op_enqueue_scripts', 50 ); ``` If priority 50 doesn't work then try increasing that to 80 or 100.
295,078
<p>I created a shortcode for user submission form. I want to submit this form without loading the page (Ajax).</p> <p>Here is my shortcode code</p> <pre><code>add_shortcode('et-test-plugin_shortcode', function($atts, $content) { $atts = shortcode_atts(array( 'name-field' =&gt; 'Name', 'phone-field' =&gt; 'Phone Number', 'email-field' =&gt; 'Email Address', 'budget-field' =&gt; 'Desired Budget', 'min-budget' =&gt; '1000', 'max-budget' =&gt; '10000', 'message-field' =&gt; 'Message', 'submit-btn-label' =&gt; 'Submit', ), $atts); ob_start(); ?&gt; &lt;form action="&lt;?php echo admin_url('admin-ajax.php'); ?&gt;" class="et_test_form" method="post"&gt; &lt;div class="row"&gt; &lt;div class="col-sm-6"&gt; &lt;input type="text" name="_name" placeholder="&lt;?php echo esc_attr($atts['name-field']) ?&gt;"&gt; &lt;/div&gt; &lt;div class="col-sm-6"&gt; &lt;input type="text" name="_phone" placeholder="&lt;?php echo esc_attr($atts['phone-field']) ?&gt;"&gt; &lt;/div&gt; &lt;div class="col-sm-6"&gt; &lt;input type="email" name="_email" placeholder="&lt;?php echo esc_attr($atts['email-field']) ?&gt;"&gt; &lt;/div&gt; &lt;div class="col-sm-6"&gt; &lt;input type="number" name="_budget" min="&lt;?php echo esc_attr($atts['min-budget']) ?&gt;" max="&lt;?php echo esc_attr($atts['max-budget']) ?&gt;" placeholder="&lt;?php echo esc_attr($atts['budget-field']) ?&gt;"&gt; &lt;/div&gt; &lt;/div&gt; &lt;textarea class="form-control" rows="3" cols="10" name="_message" placeholder="&lt;?php echo esc_attr($atts['message-field']) ?&gt;"&gt;&lt;/textarea&gt; &lt;input type="submit" name="submit" value="&lt;?php echo $atts['submit-btn-label']; ?&gt;"/&gt; &lt;div id="note"&gt;&lt;/div&gt; &lt;/form&gt; &lt;?php $html = ob_get_clean(); add_action('wp_ajax_et_test_plugin_create_post', 'et_test_plugin_create_post'); add_action('wp_ajax_nopriv_et_test_plugin_create_post', 'et_test_plugin_create_post'); function et_test_plugin_create_post() { if (isset($_POST['submit'])) { $name = !empty($_POST['_name']) ? $_POST['_name'] : ''; $phone = !empty($_POST['_phone']) ? $_POST['_phone'] : ''; $email = !empty($_POST['_email']) ? $_POST['_email'] : ''; $budget = !empty($_POST['_budget']) ? $_POST['_budget'] : ''; $message = !empty($_POST['_message']) ? $_POST['_message'] : ''; if ($name) { wp_insert_post( array( 'post_title' =&gt; wp_strip_all_tags($name) . ' submitted a form', 'post_type' =&gt; 'customer', 'post_status' =&gt; 'private', /* Or "draft", if required */ 'meta_input' =&gt; array( 'et-test-plugin_customer_name' =&gt; wp_strip_all_tags($name), 'et-test-plugin_customer_phone' =&gt; wp_strip_all_tags($phone), 'et-test-plugin_customer_email' =&gt; wp_strip_all_tags($email), 'et-test-plugin_customer_budget' =&gt; wp_strip_all_tags($budget), 'et-test-plugin_customer_message' =&gt; wp_strip_all_tags($message), ) ) ); } } } ?&gt; &lt;script type="text/javascript"&gt; var $a = jQuery.noConflict(); $a(window).load(function(){ $a(".et_test_form").submit(function(e){ e.preventDefault(); var input_data = $a(this).serialize(); $a.ajax({ type: "POST", url: "&lt;?php echo admin_url('admin-ajax.php') ?&gt;", data: input_data, action: 'et_test_plugin_create_post', success: function(alrt){ $a("#note").ajaxComplete(function(event, request, settings){ if(alrt == "OK"){ result = "Thanks for sending the message."; $a(".et_test_form").hide(); } else { result = 'Error'; } $a(this).html(result); }); } }); return false; }); }); &lt;/script&gt; &lt;?php return $html; }); </code></pre> <p>I actually don't know why this returning error. Probably, the <code>wp_ajax_et_test_plugin_create_post</code> action isn't working in the shortcode.</p>
[ { "answer_id": 295046, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>No. (or technically there might be, but in a few days there will be a question here about how to enqueue theme styles before plugin styles).</p>\n\n<p>If your styles are getting overridden by theme styles it means that you do not properly prefix your classes.</p>\n" }, { "answer_id": 295050, "author": "obiPlabon", "author_id": 135737, "author_profile": "https://wordpress.stackexchange.com/users/135737", "pm_score": 3, "selected": true, "text": "<p>It's easy to add your plugin stylesheet after theme stylesheet. If you're sure that your theme styles and plugin styles have the same selector weight (<em>theme has this style <code>.site-header { background-color: #ccc; }</code> and your plugin has this <code>.site-header { background-color: #f1f1f1; }</code></em>) then enqueuing plugin stylesheet after theme stylesheet will work.</p>\n\n<p>If you're enqueuing with <code>wp_enqueue_scripts</code> action hook then changing the hook priority parameter will do the work. Here's an example:</p>\n\n<pre><code>function op_enqueue_scripts() {\n wp_enqueue_style( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' );\n}\nadd_action( 'wp_enqueue_scripts', 'op_enqueue_scripts', 50 );\n</code></pre>\n\n<p>If priority 50 doesn't work then try increasing that to 80 or 100.</p>\n" } ]
2018/02/24
[ "https://wordpress.stackexchange.com/questions/295078", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75264/" ]
I created a shortcode for user submission form. I want to submit this form without loading the page (Ajax). Here is my shortcode code ``` add_shortcode('et-test-plugin_shortcode', function($atts, $content) { $atts = shortcode_atts(array( 'name-field' => 'Name', 'phone-field' => 'Phone Number', 'email-field' => 'Email Address', 'budget-field' => 'Desired Budget', 'min-budget' => '1000', 'max-budget' => '10000', 'message-field' => 'Message', 'submit-btn-label' => 'Submit', ), $atts); ob_start(); ?> <form action="<?php echo admin_url('admin-ajax.php'); ?>" class="et_test_form" method="post"> <div class="row"> <div class="col-sm-6"> <input type="text" name="_name" placeholder="<?php echo esc_attr($atts['name-field']) ?>"> </div> <div class="col-sm-6"> <input type="text" name="_phone" placeholder="<?php echo esc_attr($atts['phone-field']) ?>"> </div> <div class="col-sm-6"> <input type="email" name="_email" placeholder="<?php echo esc_attr($atts['email-field']) ?>"> </div> <div class="col-sm-6"> <input type="number" name="_budget" min="<?php echo esc_attr($atts['min-budget']) ?>" max="<?php echo esc_attr($atts['max-budget']) ?>" placeholder="<?php echo esc_attr($atts['budget-field']) ?>"> </div> </div> <textarea class="form-control" rows="3" cols="10" name="_message" placeholder="<?php echo esc_attr($atts['message-field']) ?>"></textarea> <input type="submit" name="submit" value="<?php echo $atts['submit-btn-label']; ?>"/> <div id="note"></div> </form> <?php $html = ob_get_clean(); add_action('wp_ajax_et_test_plugin_create_post', 'et_test_plugin_create_post'); add_action('wp_ajax_nopriv_et_test_plugin_create_post', 'et_test_plugin_create_post'); function et_test_plugin_create_post() { if (isset($_POST['submit'])) { $name = !empty($_POST['_name']) ? $_POST['_name'] : ''; $phone = !empty($_POST['_phone']) ? $_POST['_phone'] : ''; $email = !empty($_POST['_email']) ? $_POST['_email'] : ''; $budget = !empty($_POST['_budget']) ? $_POST['_budget'] : ''; $message = !empty($_POST['_message']) ? $_POST['_message'] : ''; if ($name) { wp_insert_post( array( 'post_title' => wp_strip_all_tags($name) . ' submitted a form', 'post_type' => 'customer', 'post_status' => 'private', /* Or "draft", if required */ 'meta_input' => array( 'et-test-plugin_customer_name' => wp_strip_all_tags($name), 'et-test-plugin_customer_phone' => wp_strip_all_tags($phone), 'et-test-plugin_customer_email' => wp_strip_all_tags($email), 'et-test-plugin_customer_budget' => wp_strip_all_tags($budget), 'et-test-plugin_customer_message' => wp_strip_all_tags($message), ) ) ); } } } ?> <script type="text/javascript"> var $a = jQuery.noConflict(); $a(window).load(function(){ $a(".et_test_form").submit(function(e){ e.preventDefault(); var input_data = $a(this).serialize(); $a.ajax({ type: "POST", url: "<?php echo admin_url('admin-ajax.php') ?>", data: input_data, action: 'et_test_plugin_create_post', success: function(alrt){ $a("#note").ajaxComplete(function(event, request, settings){ if(alrt == "OK"){ result = "Thanks for sending the message."; $a(".et_test_form").hide(); } else { result = 'Error'; } $a(this).html(result); }); } }); return false; }); }); </script> <?php return $html; }); ``` I actually don't know why this returning error. Probably, the `wp_ajax_et_test_plugin_create_post` action isn't working in the shortcode.
It's easy to add your plugin stylesheet after theme stylesheet. If you're sure that your theme styles and plugin styles have the same selector weight (*theme has this style `.site-header { background-color: #ccc; }` and your plugin has this `.site-header { background-color: #f1f1f1; }`*) then enqueuing plugin stylesheet after theme stylesheet will work. If you're enqueuing with `wp_enqueue_scripts` action hook then changing the hook priority parameter will do the work. Here's an example: ``` function op_enqueue_scripts() { wp_enqueue_style( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' ); } add_action( 'wp_enqueue_scripts', 'op_enqueue_scripts', 50 ); ``` If priority 50 doesn't work then try increasing that to 80 or 100.
295,086
<p>I am validating plugin to make it compatible with <code>WPCS</code>. a function which contains <code>gettext</code> placeholder returning error when i run <code>phpcs</code> command. Source code and screenshot of error is attached for reference. Maybe i am missing something or doing it in wrong way?</p> <pre><code>/** * Add Error. * * @package Mypackage * @since 0.1.0 * * @param string $code Error Code. * @param string $message Error Message. * @return object WP_Error Returns Error Object. */ function mypackage_add_error( $code, $message ) { /* translators: %s: Error Message */ return new WP_Error( $code, sprintf( esc_html__( '%s', 'mypackage' ), $message ) ); } </code></pre> <p><strong>Screenshot of Error.</strong> <a href="https://i.stack.imgur.com/ABlyJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ABlyJ.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 295046, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>No. (or technically there might be, but in a few days there will be a question here about how to enqueue theme styles before plugin styles).</p>\n\n<p>If your styles are getting overridden by theme styles it means that you do not properly prefix your classes.</p>\n" }, { "answer_id": 295050, "author": "obiPlabon", "author_id": 135737, "author_profile": "https://wordpress.stackexchange.com/users/135737", "pm_score": 3, "selected": true, "text": "<p>It's easy to add your plugin stylesheet after theme stylesheet. If you're sure that your theme styles and plugin styles have the same selector weight (<em>theme has this style <code>.site-header { background-color: #ccc; }</code> and your plugin has this <code>.site-header { background-color: #f1f1f1; }</code></em>) then enqueuing plugin stylesheet after theme stylesheet will work.</p>\n\n<p>If you're enqueuing with <code>wp_enqueue_scripts</code> action hook then changing the hook priority parameter will do the work. Here's an example:</p>\n\n<pre><code>function op_enqueue_scripts() {\n wp_enqueue_style( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' );\n}\nadd_action( 'wp_enqueue_scripts', 'op_enqueue_scripts', 50 );\n</code></pre>\n\n<p>If priority 50 doesn't work then try increasing that to 80 or 100.</p>\n" } ]
2018/02/24
[ "https://wordpress.stackexchange.com/questions/295086", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83820/" ]
I am validating plugin to make it compatible with `WPCS`. a function which contains `gettext` placeholder returning error when i run `phpcs` command. Source code and screenshot of error is attached for reference. Maybe i am missing something or doing it in wrong way? ``` /** * Add Error. * * @package Mypackage * @since 0.1.0 * * @param string $code Error Code. * @param string $message Error Message. * @return object WP_Error Returns Error Object. */ function mypackage_add_error( $code, $message ) { /* translators: %s: Error Message */ return new WP_Error( $code, sprintf( esc_html__( '%s', 'mypackage' ), $message ) ); } ``` **Screenshot of Error.** [![enter image description here](https://i.stack.imgur.com/ABlyJ.jpg)](https://i.stack.imgur.com/ABlyJ.jpg)
It's easy to add your plugin stylesheet after theme stylesheet. If you're sure that your theme styles and plugin styles have the same selector weight (*theme has this style `.site-header { background-color: #ccc; }` and your plugin has this `.site-header { background-color: #f1f1f1; }`*) then enqueuing plugin stylesheet after theme stylesheet will work. If you're enqueuing with `wp_enqueue_scripts` action hook then changing the hook priority parameter will do the work. Here's an example: ``` function op_enqueue_scripts() { wp_enqueue_style( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' ); } add_action( 'wp_enqueue_scripts', 'op_enqueue_scripts', 50 ); ``` If priority 50 doesn't work then try increasing that to 80 or 100.
295,096
<p>I'm looking to hide from search a few custom post type posts. I'm thinking that if I create a custom taxonomy for the custom post type with a term "hidden" then all posts checked will be hidden. Maybe some filter that I can add to the functions file? By chance has anyone done this or something similar? Please advise, thanks in advance :)</p> <p>Regards, Kendell </p>
[ { "answer_id": 295097, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\"><code>register_post_type()</code></a> has a <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#Arguments\" rel=\"nofollow noreferrer\">argument</a> that you can set to specify which post types you want searched, thus excluded the undesired ones. This is the simplest method, just one line:</p>\n\n<pre><code>'exclude_from_search' = true,\n</code></pre>\n\n<p>Alternative to that, you can hook into the search query itself via <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a> and then modify the search, specifying which post types you're after:</p>\n\n<pre><code>add_filter('pre_get_posts',function ($query) {\n if ($query-&gt;is_search &amp;&amp; !is_admin() )\n $query-&gt;set('post_type',array('post','page'));\n return $query;\n});\n</code></pre>\n\n<p>If you were dead set on doing the term hiding - although I don't recommend it, as it's more code with a higher chance of user error - you'd do somthing like:</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $query ) {\n global $wp_the_query;\n if($query === $wp_the_query &amp;&amp; $query-&gt;is_search() &amp;&amp; !is_admin()) {\n $tax_query = array(\n array(\n 'taxonomy' =&gt; 'your_custom_tax_name',\n 'field' =&gt; 'slug',\n 'terms' =&gt; 'hidden',\n 'operator' =&gt; 'NOT IN',\n )\n );\n $query-&gt;set( 'tax_query', $tax_query );\n }\n});\n</code></pre>\n" }, { "answer_id": 321387, "author": "Kendell Daniel", "author_id": 134826, "author_profile": "https://wordpress.stackexchange.com/users/134826", "pm_score": 0, "selected": false, "text": "<p>For the sake of anyone else searching for a solution i used the <a href=\"https://searchwp.com/\" rel=\"nofollow noreferrer\">SearchWP</a> plugin to exclude these posts.</p>\n" } ]
2018/02/25
[ "https://wordpress.stackexchange.com/questions/295096", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134826/" ]
I'm looking to hide from search a few custom post type posts. I'm thinking that if I create a custom taxonomy for the custom post type with a term "hidden" then all posts checked will be hidden. Maybe some filter that I can add to the functions file? By chance has anyone done this or something similar? Please advise, thanks in advance :) Regards, Kendell
[`register_post_type()`](https://codex.wordpress.org/Function_Reference/register_post_type) has a [argument](https://codex.wordpress.org/Function_Reference/register_post_type#Arguments) that you can set to specify which post types you want searched, thus excluded the undesired ones. This is the simplest method, just one line: ``` 'exclude_from_search' = true, ``` Alternative to that, you can hook into the search query itself via [`pre_get_posts`](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) and then modify the search, specifying which post types you're after: ``` add_filter('pre_get_posts',function ($query) { if ($query->is_search && !is_admin() ) $query->set('post_type',array('post','page')); return $query; }); ``` If you were dead set on doing the term hiding - although I don't recommend it, as it's more code with a higher chance of user error - you'd do somthing like: ``` add_action( 'pre_get_posts', function ( $query ) { global $wp_the_query; if($query === $wp_the_query && $query->is_search() && !is_admin()) { $tax_query = array( array( 'taxonomy' => 'your_custom_tax_name', 'field' => 'slug', 'terms' => 'hidden', 'operator' => 'NOT IN', ) ); $query->set( 'tax_query', $tax_query ); } }); ```
295,109
<p>I am trying to add a meta box to the "page" post type, in which I succeeded. In my meta box I would like to display a dropdown with titles from an other custom post type (named "Albums"). I also succeeded in that, but once I select a specific album in the dropdown and save the page, it changes the page permalink to the permalink of the chosen album.</p> <pre><code>&lt;?php add_action('add_meta_boxes', 'add_meta_box_album'); function add_meta_box_album() { add_meta_box('meta-box-album-id', 'Album', 'meta_box_album_callback', 'page', 'normal', 'high'); } function meta_box_album_callback($post) { $values = get_post_custom($post-&gt;ID); $mytheme_custom_select = (isset($values['mytheme_custom_select'][0]) &amp;&amp; '' !== $values['mytheme_custom_select'][0]) ? $values['mytheme_custom_select'][0] : ''; wp_nonce_field('my_meta_box_nonce', 'meta_box_nonce'); ?&gt; &lt;p&gt; &lt;label for=""&gt;Select album:&lt;/label&gt;&lt;br&gt; &lt;? $getAlbums = new WP_Query(array( 'post_type' =&gt; 'albums', )); ?&gt; &lt;select id="mytheme_custom_select" name="mytheme_custom_select"&gt; &lt;option value=""&gt;Selecht an album...&lt;/option&gt; &lt;? while ($getAlbums-&gt;have_posts()):$getAlbums-&gt;the_post(); ?&gt; &lt;option value="&lt;?php the_title($getAlbums-&gt;ID); ?&gt;" &lt;?php selected($mytheme_custom_select, the_title($getAlbums-&gt;ID), true); ?&gt;&gt;&lt;?php the_title($getAlbums-&gt;ID); ?&gt;&lt;/option&gt; &lt;? endwhile; ?&gt; &lt;? wp_reset_query(); ?&gt; &lt;/select&gt; &lt;? } add_action('save_post', 'cd_meta_box_save'); function cd_meta_box_save($post_id) { if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) return; if (!isset($_POST['meta_box_nonce']) || !wp_verify_nonce($_POST['meta_box_nonce'], 'my_meta_box_nonce')) return; if (!current_user_can('edit_post', $post_id)) return; $allowed = array( 'a' =&gt; array( 'href' =&gt; array() ) ); if (isset($_POST['mytheme_custom_select'])) { // Input var okay. update_post_meta($post_id, 'mytheme_custom_select', sanitize_text_field(wp_unslash($_POST['mytheme_custom_select']))); // Input var okay. } } </code></pre>
[ { "answer_id": 295111, "author": "obiPlabon", "author_id": 135737, "author_profile": "https://wordpress.stackexchange.com/users/135737", "pm_score": 2, "selected": true, "text": "<p>Here's the updated meta box callback function. I've used <code>get_posts()</code> instead of <code>WP_Query</code> as <code>get_posts()</code> is more performant as well as easy to use in this case. And removed <code>get_post_custom()</code> as it'll fetch all the custom metadata when you don't need them. So, I've replaced that with <code>get_post_meta()</code>. Hope your dropdown will work as expected now.</p>\n\n<p><em>I'd suggest you save post id (album id) instead of the title.</em></p>\n\n<pre><code>function meta_box_album_callback( $post ) {\n wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );\n\n $mytheme_custom_select = get_post_meta( $post-&gt;ID, 'mytheme_custom_select', true );\n $albums = get_posts( array(\n 'post_type' =&gt; 'albums',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; -1\n ) );\n ?&gt;\n\n &lt;p&gt;\n &lt;label for=\"mytheme_custom_select\"&gt;Select album:&lt;/label&gt;&lt;br&gt;\n &lt;select id=\"mytheme_custom_select\" name=\"mytheme_custom_select\"&gt;\n &lt;option value=\"\"&gt;Selecht an album...&lt;/option&gt;\n &lt;?php foreach ( $albums as $album ) : ?&gt;\n &lt;option value=\"&lt;?php echo esc_attr( $album-&gt;post_title ); ?&gt;\" &lt;?php selected( $mytheme_custom_select, esc_attr( $album-&gt;post_title ) ); ?&gt;&gt;&lt;?php echo esc_html( $album-&gt;post_title ); ?&gt;&lt;/option&gt;\n &lt;?php endforeach; ?&gt;\n &lt;/select&gt;\n &lt;/p&gt;\n\n &lt;?php\n}\n</code></pre>\n" }, { "answer_id": 384377, "author": "Zaheer Abbas", "author_id": 135489, "author_profile": "https://wordpress.stackexchange.com/users/135489", "pm_score": 0, "selected": false, "text": "<blockquote>\n<p>The above code is right but there is no save dropdown option. For\nsave you can follow below code</p>\n</blockquote>\n<pre><code>function meta_box_album_callback( $post ) {\n wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );\n\n $mytheme_custom_select = get_post_meta( $post-&gt;ID, 'mytheme_custom_select', true);\n $albums = get_posts( array(\n 'post_type' =&gt; 'albums',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; -1\n ) );\n ?&gt;\n\n &lt;p&gt;\n &lt;label for=&quot;mytheme_custom_select&quot;&gt;Select album:&lt;/label&gt;&lt;br&gt;\n &lt;select id=&quot;mytheme_custom_select&quot; name=&quot;mytheme_custom_select&quot;&gt;\n &lt;option value=&quot;&quot;&gt;Selecht an album...&lt;/option&gt;\n &lt;?php foreach ( $albums as $album ) : ?&gt;\n &lt;option value=&quot;&lt;?php echo esc_attr( $album-&gt;post_title ); ?&gt;&quot; &lt;?php selected( $mytheme_custom_select, esc_attr( $album-&gt;post_title ) ); ?&gt;&gt;&lt;?php echo esc_html( $album-&gt;post_title ); ?&gt;&lt;/option&gt;\n &lt;?php endforeach; ?&gt;\n &lt;/select&gt;\n &lt;/p&gt;\n\n &lt;?php\n}\n\n// Here you can save choose value.\n\n$mytheme_custom_select = $_POST['mytheme_custom_select'];\n update_post_meta( $post_id, 'mytheme_custom_select', $mytheme_custom_select );\n</code></pre>\n" } ]
2018/02/25
[ "https://wordpress.stackexchange.com/questions/295109", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137519/" ]
I am trying to add a meta box to the "page" post type, in which I succeeded. In my meta box I would like to display a dropdown with titles from an other custom post type (named "Albums"). I also succeeded in that, but once I select a specific album in the dropdown and save the page, it changes the page permalink to the permalink of the chosen album. ``` <?php add_action('add_meta_boxes', 'add_meta_box_album'); function add_meta_box_album() { add_meta_box('meta-box-album-id', 'Album', 'meta_box_album_callback', 'page', 'normal', 'high'); } function meta_box_album_callback($post) { $values = get_post_custom($post->ID); $mytheme_custom_select = (isset($values['mytheme_custom_select'][0]) && '' !== $values['mytheme_custom_select'][0]) ? $values['mytheme_custom_select'][0] : ''; wp_nonce_field('my_meta_box_nonce', 'meta_box_nonce'); ?> <p> <label for="">Select album:</label><br> <? $getAlbums = new WP_Query(array( 'post_type' => 'albums', )); ?> <select id="mytheme_custom_select" name="mytheme_custom_select"> <option value="">Selecht an album...</option> <? while ($getAlbums->have_posts()):$getAlbums->the_post(); ?> <option value="<?php the_title($getAlbums->ID); ?>" <?php selected($mytheme_custom_select, the_title($getAlbums->ID), true); ?>><?php the_title($getAlbums->ID); ?></option> <? endwhile; ?> <? wp_reset_query(); ?> </select> <? } add_action('save_post', 'cd_meta_box_save'); function cd_meta_box_save($post_id) { if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return; if (!isset($_POST['meta_box_nonce']) || !wp_verify_nonce($_POST['meta_box_nonce'], 'my_meta_box_nonce')) return; if (!current_user_can('edit_post', $post_id)) return; $allowed = array( 'a' => array( 'href' => array() ) ); if (isset($_POST['mytheme_custom_select'])) { // Input var okay. update_post_meta($post_id, 'mytheme_custom_select', sanitize_text_field(wp_unslash($_POST['mytheme_custom_select']))); // Input var okay. } } ```
Here's the updated meta box callback function. I've used `get_posts()` instead of `WP_Query` as `get_posts()` is more performant as well as easy to use in this case. And removed `get_post_custom()` as it'll fetch all the custom metadata when you don't need them. So, I've replaced that with `get_post_meta()`. Hope your dropdown will work as expected now. *I'd suggest you save post id (album id) instead of the title.* ``` function meta_box_album_callback( $post ) { wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' ); $mytheme_custom_select = get_post_meta( $post->ID, 'mytheme_custom_select', true ); $albums = get_posts( array( 'post_type' => 'albums', 'post_status' => 'publish', 'posts_per_page' => -1 ) ); ?> <p> <label for="mytheme_custom_select">Select album:</label><br> <select id="mytheme_custom_select" name="mytheme_custom_select"> <option value="">Selecht an album...</option> <?php foreach ( $albums as $album ) : ?> <option value="<?php echo esc_attr( $album->post_title ); ?>" <?php selected( $mytheme_custom_select, esc_attr( $album->post_title ) ); ?>><?php echo esc_html( $album->post_title ); ?></option> <?php endforeach; ?> </select> </p> <?php } ```
295,152
<p>I'm trying to change the default 10-day expiration for the cookie that allows a user to repeatedly view the content on a password-protected WP page without having to re-enter the page password during the default 10-day period. Rather than 10 days, I'd like to re-set the expiration to 30 seconds.</p> <p>The WP code reference is <a href="https://developer.wordpress.org/reference/hooks/post_password_expires/" rel="nofollow noreferrer">here</a>:</p> <pre><code>apply_filters( 'post_password_expires', int $expires ) </code></pre> <p>This is what I have tried, without success:</p> <pre><code>function custom_post_password_expires() { return time() + 30; // Expire in 30 seconds } apply_filters('post_password_expires', 'custom_post_password_expires'); </code></pre> <p>I've read the answers to previous similar questions, and none seem to apply or to provide a solution that works with the current version of WP. I suspect that the correct answer is very simple, but so far I'm not finding it. (Note: I am not an advanced developer, so I'd appreciate replies that are easy to understand :)</p> <p>Thanks.</p>
[ { "answer_id": 295135, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>There is no reason for your design, but the core of your problem is that (I assume) people are trying to use a free tier of the API instead of properly paying for its use and removing the ridiculous restrictions.</p>\n\n<p>Anyway, the solution is fairly simple, run your cron every half an hour, allocate to your import process unlimited time (and you might need to instruct your users to increase memory limit), and just loop until you got all the requested data with a second delay <a href=\"http://php.net/manual/en/function.sleep.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.sleep.php</a> between each request.</p>\n\n<p>Even the worst case of each request taking 5 seconds to complete, the whole thing should be done in 5 minutes.</p>\n\n<p>As for the user view, you should keep new info in some kind of limbo state until you got all of it, and only then make it presentable.</p>\n" }, { "answer_id": 386222, "author": "James John", "author_id": 171509, "author_profile": "https://wordpress.stackexchange.com/users/171509", "pm_score": 0, "selected": false, "text": "<p>Disable WP Cron from running on users' traffic. Then run cron through a cron or timed job somewhere else. You can achieve this by adding this to your <code>wp-config.php</code></p>\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre>\n<p>Then set up a cron job to hit this URL - <code>https://domain.com/wp-cron.php?doing_wp_cron</code> at your desired time intervals. A quick <code>wget</code> code below:</p>\n<pre><code>wget -q -O - https://domain.com/wp-cron.php?doing_wp_cron &gt;/dev/null 2&gt;&amp;1\n</code></pre>\n<p>I suggest every minute, as all other cron jobs in the WordPress installation will be dependent on it</p>\n" } ]
2018/02/25
[ "https://wordpress.stackexchange.com/questions/295152", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137545/" ]
I'm trying to change the default 10-day expiration for the cookie that allows a user to repeatedly view the content on a password-protected WP page without having to re-enter the page password during the default 10-day period. Rather than 10 days, I'd like to re-set the expiration to 30 seconds. The WP code reference is [here](https://developer.wordpress.org/reference/hooks/post_password_expires/): ``` apply_filters( 'post_password_expires', int $expires ) ``` This is what I have tried, without success: ``` function custom_post_password_expires() { return time() + 30; // Expire in 30 seconds } apply_filters('post_password_expires', 'custom_post_password_expires'); ``` I've read the answers to previous similar questions, and none seem to apply or to provide a solution that works with the current version of WP. I suspect that the correct answer is very simple, but so far I'm not finding it. (Note: I am not an advanced developer, so I'd appreciate replies that are easy to understand :) Thanks.
There is no reason for your design, but the core of your problem is that (I assume) people are trying to use a free tier of the API instead of properly paying for its use and removing the ridiculous restrictions. Anyway, the solution is fairly simple, run your cron every half an hour, allocate to your import process unlimited time (and you might need to instruct your users to increase memory limit), and just loop until you got all the requested data with a second delay <http://php.net/manual/en/function.sleep.php> between each request. Even the worst case of each request taking 5 seconds to complete, the whole thing should be done in 5 minutes. As for the user view, you should keep new info in some kind of limbo state until you got all of it, and only then make it presentable.
295,189
<p>I know this has been asked and answered before but the solutions are not working for my so I was wondering if something has changed or if I am doing something wrong. Want to display my Categories, Child Cats, Grand Child-Cats. This is my code:</p> <pre><code>function list_areas () { $provincearg = array( 'taxonomy' =&gt; 'area', 'hide_empty' =&gt; false, 'parent'=&gt; 0, ); $provinces = get_terms ($provincearg); foreach ($provinces as $province) { echo '&lt;h2&gt;' .$province -&gt; name. '&lt;/h2&gt;'; $municipalarg = array ( 'taxonomy' =&gt; 'area', 'hide_empty' =&gt; false, 'parent'=&gt; $province -&gt; term_id, ); $municipalities = get_terms ($municipalarg); echo '&lt;ul&gt;'; foreach ($municipalities as $municipality) { echo '&lt;li&gt;' .$municipality -&gt; name. '&lt;/li&gt;'; } echo '&lt;ul&gt;'; } } </code></pre> <p>It outputs the Category but not the sub categories. I even went as far as puting in the 'parent' id, when I do this nothing gets displayed. </p> <p>Any help will be appreciated.</p>
[ { "answer_id": 295135, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>There is no reason for your design, but the core of your problem is that (I assume) people are trying to use a free tier of the API instead of properly paying for its use and removing the ridiculous restrictions.</p>\n\n<p>Anyway, the solution is fairly simple, run your cron every half an hour, allocate to your import process unlimited time (and you might need to instruct your users to increase memory limit), and just loop until you got all the requested data with a second delay <a href=\"http://php.net/manual/en/function.sleep.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.sleep.php</a> between each request.</p>\n\n<p>Even the worst case of each request taking 5 seconds to complete, the whole thing should be done in 5 minutes.</p>\n\n<p>As for the user view, you should keep new info in some kind of limbo state until you got all of it, and only then make it presentable.</p>\n" }, { "answer_id": 386222, "author": "James John", "author_id": 171509, "author_profile": "https://wordpress.stackexchange.com/users/171509", "pm_score": 0, "selected": false, "text": "<p>Disable WP Cron from running on users' traffic. Then run cron through a cron or timed job somewhere else. You can achieve this by adding this to your <code>wp-config.php</code></p>\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre>\n<p>Then set up a cron job to hit this URL - <code>https://domain.com/wp-cron.php?doing_wp_cron</code> at your desired time intervals. A quick <code>wget</code> code below:</p>\n<pre><code>wget -q -O - https://domain.com/wp-cron.php?doing_wp_cron &gt;/dev/null 2&gt;&amp;1\n</code></pre>\n<p>I suggest every minute, as all other cron jobs in the WordPress installation will be dependent on it</p>\n" } ]
2018/02/26
[ "https://wordpress.stackexchange.com/questions/295189", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107025/" ]
I know this has been asked and answered before but the solutions are not working for my so I was wondering if something has changed or if I am doing something wrong. Want to display my Categories, Child Cats, Grand Child-Cats. This is my code: ``` function list_areas () { $provincearg = array( 'taxonomy' => 'area', 'hide_empty' => false, 'parent'=> 0, ); $provinces = get_terms ($provincearg); foreach ($provinces as $province) { echo '<h2>' .$province -> name. '</h2>'; $municipalarg = array ( 'taxonomy' => 'area', 'hide_empty' => false, 'parent'=> $province -> term_id, ); $municipalities = get_terms ($municipalarg); echo '<ul>'; foreach ($municipalities as $municipality) { echo '<li>' .$municipality -> name. '</li>'; } echo '<ul>'; } } ``` It outputs the Category but not the sub categories. I even went as far as puting in the 'parent' id, when I do this nothing gets displayed. Any help will be appreciated.
There is no reason for your design, but the core of your problem is that (I assume) people are trying to use a free tier of the API instead of properly paying for its use and removing the ridiculous restrictions. Anyway, the solution is fairly simple, run your cron every half an hour, allocate to your import process unlimited time (and you might need to instruct your users to increase memory limit), and just loop until you got all the requested data with a second delay <http://php.net/manual/en/function.sleep.php> between each request. Even the worst case of each request taking 5 seconds to complete, the whole thing should be done in 5 minutes. As for the user view, you should keep new info in some kind of limbo state until you got all of it, and only then make it presentable.
295,221
<p>I have this code that pulls a user's gravatar:</p> <pre><code>if( $current_user-&gt;ID == 0 ) { // Not logged in. echo '&lt;p&gt;&lt;img src="'.get_stylesheet_directory_uri().'/img/wpb-default-gravatar.png" alt="תמונת פרופיל"&gt;&lt;/p&gt;'; echo '&lt;p&gt;רוצה למכור?&lt;/p&gt;'; echo '&lt;p&gt;&lt;a href="חשבון-חנות"&gt;פתח חנות&lt;/a&gt;&lt;/p&gt;'; } else { $current_user = wp_get_current_user(); $args = array( 'height' =&gt; 50, 'width' =&gt; 50, 'class' =&gt; 'gravatar', 'scheme' =&gt; 'https' ); echo '&lt;p&gt;'.get_avatar( $current_user-&gt;ID, 50, '', 'תמונת פרופיל', $args ).'&lt;/p&gt;'; echo '&lt;p&gt;היי, ' . $current_user-&gt;user_firstname.'!&lt;/p&gt;'; echo '&lt;p&gt;&lt;a href="'.get_permalink(get_option("woocommerce_myaccount_page_id")).'"&gt;חשבון&lt;/a&gt; &lt;span&gt;|&lt;/span&gt; &lt;a href="'.wp_logout_url().'"&gt;התנתק&lt;/a&gt;&lt;/p&gt;'; } </code></pre> <p>The function <code>get_avatar</code> result link is this: <strong><a href="http://i2.wp.com/nivbook.odedta.com/wp-content/themes/total-child-theme-master/img/wpb-default-gravatar.png" rel="nofollow noreferrer">http://i2.wp.com/nivbook.odedta.com/wp-content/themes/total-child-theme-master/img/wpb-default-gravatar.png</a></strong></p> <p>What is <strong><a href="http://i2.wp.com/" rel="nofollow noreferrer">http://i2.wp.com/</a></strong> doing in that link and how do I get rid of it?</p> <p>Thanks</p>
[ { "answer_id": 295224, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": false, "text": "<p>As the filename suggests, it's a default for when someone does not have a gravatar assigned. It is set up in your child theme and looks to be improperly set. You should search through the child theme files to find 'wpb-default-gravatar.png' and from there figure out what is adding the extra domain.</p>\n\n<p>If this is a child theme you've purchased and not a custom one, I would highly recommend letting the theme author know and if you're able to solve the code problem, send them a pull request or the finished code with an explanation of what problem you were solving so they can include it in the next update.</p>\n" }, { "answer_id": 295319, "author": "Beee", "author_id": 103402, "author_profile": "https://wordpress.stackexchange.com/users/103402", "pm_score": 0, "selected": false, "text": "<p>Gravatar comes from the people of Wordpress. I don't find it weird they serve a default gravatar (which is requested from a Wordpress site) from a Wordpress domain.</p>\n\n<p>Why do you want to get rid of it ?</p>\n" } ]
2018/02/26
[ "https://wordpress.stackexchange.com/questions/295221", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84049/" ]
I have this code that pulls a user's gravatar: ``` if( $current_user->ID == 0 ) { // Not logged in. echo '<p><img src="'.get_stylesheet_directory_uri().'/img/wpb-default-gravatar.png" alt="תמונת פרופיל"></p>'; echo '<p>רוצה למכור?</p>'; echo '<p><a href="חשבון-חנות">פתח חנות</a></p>'; } else { $current_user = wp_get_current_user(); $args = array( 'height' => 50, 'width' => 50, 'class' => 'gravatar', 'scheme' => 'https' ); echo '<p>'.get_avatar( $current_user->ID, 50, '', 'תמונת פרופיל', $args ).'</p>'; echo '<p>היי, ' . $current_user->user_firstname.'!</p>'; echo '<p><a href="'.get_permalink(get_option("woocommerce_myaccount_page_id")).'">חשבון</a> <span>|</span> <a href="'.wp_logout_url().'">התנתק</a></p>'; } ``` The function `get_avatar` result link is this: **<http://i2.wp.com/nivbook.odedta.com/wp-content/themes/total-child-theme-master/img/wpb-default-gravatar.png>** What is **<http://i2.wp.com/>** doing in that link and how do I get rid of it? Thanks
As the filename suggests, it's a default for when someone does not have a gravatar assigned. It is set up in your child theme and looks to be improperly set. You should search through the child theme files to find 'wpb-default-gravatar.png' and from there figure out what is adding the extra domain. If this is a child theme you've purchased and not a custom one, I would highly recommend letting the theme author know and if you're able to solve the code problem, send them a pull request or the finished code with an explanation of what problem you were solving so they can include it in the next update.
295,234
<p>I'm relatively new to creating a theme with WordPress, and I've been adding all the stylesheets (main and for each page) with the old <code>echo get_stylesheet_uri();</code>. But I find out that this isn't the recommended way to do, and instead, to add all the styles within functions.php.</p> <p>Old method (working):</p> <pre><code>&lt;link rel="stylesheet" href="&lt;?php echo get_stylesheet_uri(); ?&gt;"&gt; </code></pre> <p>New method (not working):</p> <pre><code>&lt;?php add_theme_support('post-thumbnails'); //Posts thumbnails //Custom excerpt function get_excerpt($excerpt, $length, $more_char = '...'){ return mb_strimwidth($excerpt, 0, $length, $more_char); } function theme_styles() { //METHOD 1 //wp_register_style( 'main-style', get_template_directory_uri() . '/style.css'); //wp_enqueue_style( 'main-style'); //METHOD 2 wp_enqueue_style( 'main-style', get_template_directory_uri() . '/style.css' ); } add_action( 'wp_enqueue_scripts', 'theme_styles' ); ?&gt; </code></pre> <p>I tried both methods above and none worked. Is there anything wrong besides my bad English?</p> <hr> <p><strong>Edit (SOLVED)</strong></p> <p>Thanks to <a href="https://wordpress.stackexchange.com/users/106269/nathan-johnson">Nathan Johnson</a> who found the error. I wasn't using <code>wp_head()</code> on my <code>header.php</code>, therefore, WordPress wasn't finding where to put the enqueue style. Rookie error.</p>
[ { "answer_id": 295239, "author": "maheshwaghmare", "author_id": 52167, "author_profile": "https://wordpress.stackexchange.com/users/52167", "pm_score": 0, "selected": false, "text": "<p>Use </p>\n\n<pre><code>wp_enqueue_style( 'theme-slug', get_stylesheet_uri() );\n</code></pre>\n\n<p>Building a WordPress theme always use unique theme prefix for everything including function, class, constants, option etc.</p>\n\n<p>Also, read the theme development documentation on wp.org</p>\n\n<p>See <a href=\"https://developer.wordpress.org/themes/getting-started/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/getting-started/</a></p>\n\n<p><strong>Updated (27-Feb-2018)</strong> Use unique prefix for your theme/plugin which avoid the conflict in between other theme/plugin.</p>\n" }, { "answer_id": 343925, "author": "Motahar Hossain", "author_id": 142970, "author_profile": "https://wordpress.stackexchange.com/users/142970", "pm_score": 1, "selected": false, "text": "<p>Before adding any file you must seperate your <code>header.php</code> file &amp; add <code>wp_head()</code> function in <code>header.php</code> file</p>\n<pre><code> // Load the theme stylesheets\n function theme_styles() \n { \n // Example of loading a custom css file for homepage just on the homepage\n wp_register_style( 'custom', get_template_directory_uri() . '/css/custom.css' );\n if(is_page('home')) {\n wp_enqueue_style('custom');\n }\n // Example of loading a main css file on all pages\n wp_enqueue_style( 'main', get_template_directory_uri() . '/css/main.css' );\n\n // Example of loading js files on all pages\n wp_enqueue_script( 'scripts', get_template_directory_uri() . '/js/scripts.js');\n \n}\n add_action('wp_enqueue_scripts', 'theme_styles');\n</code></pre>\n<p>In this case the js files will be loaded on inside the <code>&lt;head&gt;&lt;/head&gt;</code> tag. If you want to load the js files in ths bottom you must need to add <code>&lt;?php wp_footer() ?&gt;</code> on your footer. And then you need to call the <code>wp_enqueue_script()</code> this way.</p>\n<pre><code>wp_enqueue_script( 'scripts', get_template_directory_uri() . '/js/scripts.js','','1.1', true); \n</code></pre>\n<p>This <code>true</code> boolean is the answer of the <code>$in_footer</code> parameter of <code>wp_enqueue_script()</code> function. ( <a href=\"https://developer.wordpress.org/themes/basics/including-css-javascript/#scripts\" rel=\"nofollow noreferrer\">See Doc</a> )</p>\n" } ]
2018/02/26
[ "https://wordpress.stackexchange.com/questions/295234", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130486/" ]
I'm relatively new to creating a theme with WordPress, and I've been adding all the stylesheets (main and for each page) with the old `echo get_stylesheet_uri();`. But I find out that this isn't the recommended way to do, and instead, to add all the styles within functions.php. Old method (working): ``` <link rel="stylesheet" href="<?php echo get_stylesheet_uri(); ?>"> ``` New method (not working): ``` <?php add_theme_support('post-thumbnails'); //Posts thumbnails //Custom excerpt function get_excerpt($excerpt, $length, $more_char = '...'){ return mb_strimwidth($excerpt, 0, $length, $more_char); } function theme_styles() { //METHOD 1 //wp_register_style( 'main-style', get_template_directory_uri() . '/style.css'); //wp_enqueue_style( 'main-style'); //METHOD 2 wp_enqueue_style( 'main-style', get_template_directory_uri() . '/style.css' ); } add_action( 'wp_enqueue_scripts', 'theme_styles' ); ?> ``` I tried both methods above and none worked. Is there anything wrong besides my bad English? --- **Edit (SOLVED)** Thanks to [Nathan Johnson](https://wordpress.stackexchange.com/users/106269/nathan-johnson) who found the error. I wasn't using `wp_head()` on my `header.php`, therefore, WordPress wasn't finding where to put the enqueue style. Rookie error.
Before adding any file you must seperate your `header.php` file & add `wp_head()` function in `header.php` file ``` // Load the theme stylesheets function theme_styles() { // Example of loading a custom css file for homepage just on the homepage wp_register_style( 'custom', get_template_directory_uri() . '/css/custom.css' ); if(is_page('home')) { wp_enqueue_style('custom'); } // Example of loading a main css file on all pages wp_enqueue_style( 'main', get_template_directory_uri() . '/css/main.css' ); // Example of loading js files on all pages wp_enqueue_script( 'scripts', get_template_directory_uri() . '/js/scripts.js'); } add_action('wp_enqueue_scripts', 'theme_styles'); ``` In this case the js files will be loaded on inside the `<head></head>` tag. If you want to load the js files in ths bottom you must need to add `<?php wp_footer() ?>` on your footer. And then you need to call the `wp_enqueue_script()` this way. ``` wp_enqueue_script( 'scripts', get_template_directory_uri() . '/js/scripts.js','','1.1', true); ``` This `true` boolean is the answer of the `$in_footer` parameter of `wp_enqueue_script()` function. ( [See Doc](https://developer.wordpress.org/themes/basics/including-css-javascript/#scripts) )
295,247
<p>How would I change every post so that they had the same, hard-coded featured image?! Say this cigar:</p> <p><a href="https://www.cigarsofcuba.co.uk/acatalog/slide1.jpeg" rel="nofollow noreferrer">https://www.cigarsofcuba.co.uk/acatalog/slide1.jpeg</a></p> <p>(I don't actually want to do this - but it's a stumbling block in something more complex.) </p> <p>I think it ought to be this:</p> <pre><code>function set_post_thumbnail( $post, $thumbnail_id ) { $thumbnail_id = "https://www.cigarsofcuba.co.uk/acatalog/slide1.jpeg"; update_post_meta( $post-&gt;ID, '_thumbnail_id', $thumbnail_id ); } add_action( 'save_post', 'set_post_thumbnail' ); </code></pre> <p>... but no cigar. What am I missing? Thanks!</p>
[ { "answer_id": 295253, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<p><strong>Method 1: Using the <code>publish_post</code> hook* and <code>media_sideload_image()</code></strong> </p>\n\n<p>Here we will upload an image from a URL, attach it to the post, and set it as the featured image when the post is published.</p>\n\n<p>*Actually, we're using the dynamic hook <code>{$new_status}_{$post-&gt;post_type}</code>, which refers transitioning a <code>post</code> post type to the <code>publish</code> status. See <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/post.php#L4230\" rel=\"nofollow noreferrer\"><code>wp-includes/post.php</code></a> for details.</p>\n\n<p>This example code applies when publishing the post type <code>post</code>. A check is in place so that we do not automatically assign the featured image if one has been manually set. Feel free to customize this as desired.</p>\n\n<pre><code>/**\n * Download image, attach it to the current post, and assign it as featured image\n * upon publishing the post.\n *\n * The dynamic portions of the hook name, `$new_status` and `$post-&gt;post_type`,\n * refer to the new post status and post type, respectively.\n *\n * Please note: When this action is hooked using a particular post status (like\n * 'publish', as `publish_{$post-&gt;post_type}`), it will fire both when a post is\n * first transitioned to that status from something else, as well as upon\n * subsequent post updates (old and new status are both the same).\n *\n * @param int $post_id Post ID.\n * @param WP_Post $post Post object.\n */\nadd_action( 'publish_post', 'wpse_default_featured_image', 10, 2 );\nfunction wpse_default_featured_image( $post_id, $post ) {\n // Bail if there is already a post thumbnail set.\n $current_post_thumbnail = get_post_thumbnail_id( $post_id );\n if ( '' !== $current_post_thumbnail ) {\n return;\n }\n\n $url = 'https://www.cigarsofcuba.co.uk/acatalog/slide1.jpeg';\n $title = \"The default featured image.\";\n\n $image = media_sideload_image( $url, $post_id, $title, 'id' );\n set_post_thumbnail( $post_id, $image );\n}\n</code></pre>\n\n<p><strong>Method 2: Applying a filter to the post thumbnail.</strong></p>\n\n<p>By using a filter, we can \"virtually\" set the post thumbnail. This method makes it easier to change the post thumbnail on the fly for all posts.</p>\n\n<p><strong>Filter 1:</strong> <code>post_thumbnail_html</code></p>\n\n<p>The <code>post_thumbnail_html</code> filter can be used to override the HTML output for the post thumbnail:</p>\n\n<pre><code>/**\n * Filters the post thumbnail HTML.\n *\n * @param string $html The post thumbnail HTML.\n * @param int $post_id The post ID.\n * @param string $post_thumbnail_id The post thumbnail ID.\n * @param string|array $size The post thumbnail size. Image size or array of width and height\n * values (in that order). Default 'post-thumbnail'.\n * @param string $attr Query string of attributes.\n */\nadd_filter( 'post_thumbnail_html', 'wpse_post_thumbnail_html', 10, 5 );\nfunction wpse_post_thumbnail_html( $html, $post_id, $post_thumbnail_id, $size, $attr ) {\n return '&lt;img src=\"https://www.cigarsofcuba.co.uk/acatalog/slide1.jpeg\" alt=\"Have a cigar\"&gt;';\n}\n</code></pre>\n\n<p><strong>Filter 2:</strong> Using <code>get_post_metadata</code> on the <code>_thumbnail_id</code> meta key.</p>\n\n<p>Here's another approach that overrides each post's thumbnail ID with a different ID.</p>\n\n<p>I'd suggest implementing a Customizer setting or options page that allows the special thumbnail image to be uploaded/selected (locally, from a URL, or from the medial library). Then you can use the <code>get_post_metadata</code> filter to modify the value associated with each post thumbnail's meta key <code>_thumbnail_id</code>:</p>\n\n<pre><code>/**\n * Dynamic hook: \"get_{$meta_type}_metadata\"\n * \n * Filters whether to retrieve metadata of a specific type.\n * \n * The dynamic portion of the hook, `$meta_type`, refers to the meta\n * object type (comment, post, or user). Returning a non-null value\n * will effectively short-circuit the function.\n *\n * @param null|array|string $value The value get_metadata() should return - a single metadata value,\n * or an array of values.\n * @param int $object_id Object ID.\n * @param string $meta_key Meta key.\n * @param bool $single Whether to return only the first value of the specified $meta_key.\n */\nadd_filter( 'get_post_metadata', 'wpse_featured_image_id_override', 100, 4 );\nfunction wpse_featured_image_id_override( $value, $object_id, $meta_key, $single ) {\n $thumbnail_id_key = '_thumbnail_id';\n\n // Bail if this is not the correct meta key. Return the original value immediately.\n if ( ! isset( $meta_key ) || $thumbnail_id_key !== $meta_key ) {\n return $value;\n }\n\n // Add additional guard clauses if necessary... (check post type, etc.)\n\n // Get the id for an image uploaded elsewhere.\n // This could be pulled from the customizer or a plugin options page.\n return 807; // Example ID\n}\n</code></pre>\n" }, { "answer_id": 295335, "author": "Phill Healey", "author_id": 55152, "author_profile": "https://wordpress.stackexchange.com/users/55152", "pm_score": 2, "selected": false, "text": "<p>You could simply overwrite the featured image (whether one is set or not) on saving the page / post with this:</p>\n\n<pre><code>//this is called on saving page/post\nadd_action('save_post', 'force_featured_image');\n\nfunction force_featured_image( $post_id ){\n //set the featured image\n set_post_thumbnail( $post_id, [image_id] );\n}\n</code></pre>\n\n<p><strong><em>NOTE</em></strong>\nReplace '[image_id]' with your image id.</p>\n" }, { "answer_id": 342925, "author": "Ajay Prajapati", "author_id": 171899, "author_profile": "https://wordpress.stackexchange.com/users/171899", "pm_score": 0, "selected": false, "text": "<pre><code>function wpb_autolink_featured_images( $html, $post_id, $post_image_id ) {\n if (! is_singular()) {\n $html = '&lt;a href=\"' . get_permalink( $post_id ) . '\" title=\"' \n . esc_attr( get_the_title( $post_id ) ) . '\"&gt;' . $html . '&lt;/a&gt;';\n return $html;\n } else {\n return $html;\n }\n}\nadd_filter( 'post_thumbnail_html', 'wpb_autolink_featured_images', 10, 3 );\n</code></pre>\n" } ]
2018/02/26
[ "https://wordpress.stackexchange.com/questions/295247", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121694/" ]
How would I change every post so that they had the same, hard-coded featured image?! Say this cigar: <https://www.cigarsofcuba.co.uk/acatalog/slide1.jpeg> (I don't actually want to do this - but it's a stumbling block in something more complex.) I think it ought to be this: ``` function set_post_thumbnail( $post, $thumbnail_id ) { $thumbnail_id = "https://www.cigarsofcuba.co.uk/acatalog/slide1.jpeg"; update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id ); } add_action( 'save_post', 'set_post_thumbnail' ); ``` ... but no cigar. What am I missing? Thanks!
**Method 1: Using the `publish_post` hook\* and `media_sideload_image()`** Here we will upload an image from a URL, attach it to the post, and set it as the featured image when the post is published. \*Actually, we're using the dynamic hook `{$new_status}_{$post->post_type}`, which refers transitioning a `post` post type to the `publish` status. See [`wp-includes/post.php`](https://github.com/WordPress/WordPress/blob/master/wp-includes/post.php#L4230) for details. This example code applies when publishing the post type `post`. A check is in place so that we do not automatically assign the featured image if one has been manually set. Feel free to customize this as desired. ``` /** * Download image, attach it to the current post, and assign it as featured image * upon publishing the post. * * The dynamic portions of the hook name, `$new_status` and `$post->post_type`, * refer to the new post status and post type, respectively. * * Please note: When this action is hooked using a particular post status (like * 'publish', as `publish_{$post->post_type}`), it will fire both when a post is * first transitioned to that status from something else, as well as upon * subsequent post updates (old and new status are both the same). * * @param int $post_id Post ID. * @param WP_Post $post Post object. */ add_action( 'publish_post', 'wpse_default_featured_image', 10, 2 ); function wpse_default_featured_image( $post_id, $post ) { // Bail if there is already a post thumbnail set. $current_post_thumbnail = get_post_thumbnail_id( $post_id ); if ( '' !== $current_post_thumbnail ) { return; } $url = 'https://www.cigarsofcuba.co.uk/acatalog/slide1.jpeg'; $title = "The default featured image."; $image = media_sideload_image( $url, $post_id, $title, 'id' ); set_post_thumbnail( $post_id, $image ); } ``` **Method 2: Applying a filter to the post thumbnail.** By using a filter, we can "virtually" set the post thumbnail. This method makes it easier to change the post thumbnail on the fly for all posts. **Filter 1:** `post_thumbnail_html` The `post_thumbnail_html` filter can be used to override the HTML output for the post thumbnail: ``` /** * Filters the post thumbnail HTML. * * @param string $html The post thumbnail HTML. * @param int $post_id The post ID. * @param string $post_thumbnail_id The post thumbnail ID. * @param string|array $size The post thumbnail size. Image size or array of width and height * values (in that order). Default 'post-thumbnail'. * @param string $attr Query string of attributes. */ add_filter( 'post_thumbnail_html', 'wpse_post_thumbnail_html', 10, 5 ); function wpse_post_thumbnail_html( $html, $post_id, $post_thumbnail_id, $size, $attr ) { return '<img src="https://www.cigarsofcuba.co.uk/acatalog/slide1.jpeg" alt="Have a cigar">'; } ``` **Filter 2:** Using `get_post_metadata` on the `_thumbnail_id` meta key. Here's another approach that overrides each post's thumbnail ID with a different ID. I'd suggest implementing a Customizer setting or options page that allows the special thumbnail image to be uploaded/selected (locally, from a URL, or from the medial library). Then you can use the `get_post_metadata` filter to modify the value associated with each post thumbnail's meta key `_thumbnail_id`: ``` /** * Dynamic hook: "get_{$meta_type}_metadata" * * Filters whether to retrieve metadata of a specific type. * * The dynamic portion of the hook, `$meta_type`, refers to the meta * object type (comment, post, or user). Returning a non-null value * will effectively short-circuit the function. * * @param null|array|string $value The value get_metadata() should return - a single metadata value, * or an array of values. * @param int $object_id Object ID. * @param string $meta_key Meta key. * @param bool $single Whether to return only the first value of the specified $meta_key. */ add_filter( 'get_post_metadata', 'wpse_featured_image_id_override', 100, 4 ); function wpse_featured_image_id_override( $value, $object_id, $meta_key, $single ) { $thumbnail_id_key = '_thumbnail_id'; // Bail if this is not the correct meta key. Return the original value immediately. if ( ! isset( $meta_key ) || $thumbnail_id_key !== $meta_key ) { return $value; } // Add additional guard clauses if necessary... (check post type, etc.) // Get the id for an image uploaded elsewhere. // This could be pulled from the customizer or a plugin options page. return 807; // Example ID } ```
295,284
<p>I'm building a custom theme using Xampp on my localhost. I've got everything sorted for the site, except for this permalinks issue.</p> <p>Currently, the site uses the Advanced Custom Fields plugin and has some dependencies on this plugin to work.</p> <p>When using plain permalinks, the site works fine. When I change to "Post name" permalinks, all pages on the site return 404 errors, except for the Custom Post Types that I've setup, which function as normal pages. </p> <p>I can revert back to one of the default themes, and the permalinks start working as normal, so I'm fairly confident that it's a theme issue. </p> <p>When I replace the functions.php file with a blank file (no php code inside), the site loads minus the styles as expected, but all the links simply refresh the page instead of attempting to navigate to any of the pages. </p> <p>Just to confirm a few things...</p> <ul> <li>mod_rewrite is turned on in Apache, although I've also set this up on a separate Microsoft server and IIS, so I don't think this is the issue.</li> <li>I've disabled all plugins (including the advanced custom posts), and the 404 issue still occurs</li> <li>The pages don't return 404's when switched to the default theme</li> <li>The home page renders normally regardless of what settings I use. </li> <li>I'm getting the 404.php page (that I setup) returned, and not the WordPress 404 page</li> <li>I've tried adding rules to flush the rewrite rules</li> <li>I've tried setting global permalink rewrite structure to /%postname% which didn't make a difference</li> <li>WordPress can write to the .htaccess file. This definitely changes or is created locally when permalink settings are updated so this isn't an issue either. </li> </ul> <p>Below is my functions.php code which initializes the Custom Post to WordPress - this is pretty much the only thing that I can think of that must contain some sort of error, as all of the above steps that I've tried don't seem to have any effect.</p> <pre><code>/* Add custom post type 'Products' to Tower/NPI Theme */ add_action('init', 'create_postTypeProducts', 0 ); function create_postTypeProducts() { $labels = array( 'name' =&gt; _x( 'Products', 'Post Type General Name', 'Tower-NPI'), 'singular name' =&gt; _x( 'Product', 'Singular Name', 'Tower-NPI'), 'menu_name' =&gt; _x( 'Products', 'admin menu', 'Tower-NPI'), 'name_admin_bar' =&gt; _x( 'Products', 'add new on admin bar', 'Tower-NPI' ), 'all_items' =&gt; __( 'All Products', 'Tower-NPI' ), 'view_item' =&gt; __( 'View Products', 'Tower-NPI' ), 'add_new_item' =&gt; _x( 'Add New Product', 'Tower-NPI' ), 'add_new' =&gt; _x( 'Add Product', 'Tower-NPI' ), 'edit_item' =&gt; __( 'Edit Product', 'Tower-NPI' ), 'update_item' =&gt; __( 'Update Product', 'Tower-NPI' ), 'search_items' =&gt; __( 'Search for Products', 'Tower-NPI' ), 'not_found' =&gt; __( 'Not Found', 'Tower-NPI' ), 'not_found_in_trash' =&gt; __( 'Not found in Trash', 'Tower-NPI' ), ); $args = array( 'label' =&gt; __('Products', 'Tower-NPI'), 'description' =&gt; __('A list of products associated with the Tower/NPI Theme.', 'Tower-NPI'), 'labels' =&gt; $labels, 'supports' =&gt; array( 'title', 'editor', 'excerpt', 'revisions', 'author', 'thumbnail', 'custom-fields', 'post-formats', 'page-attributes' ), 'hierarchical' =&gt; true, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'show_in_nav_menus' =&gt; true, 'show_in_admin_bar' =&gt; true, 'menu_position' =&gt; 21, 'menu_icon' =&gt; 'dashicons-admin-home', 'can_export' =&gt; true, 'has_archive' =&gt; true, 'exclude_from_search' =&gt; false, 'publicly_queryable' =&gt; true, 'capability_type' =&gt; 'post', 'show_in_rest' =&gt; true, 'rest_base' =&gt; 'products-api', 'rest_controller_class' =&gt; 'WP_REST_Posts_Controller', 'rewrite' =&gt; array('slug' =&gt; '/', 'with_front' =&gt; false,) ); register_post_type('Products', $args ); } /* Flush rewrite rules on theme switch */ function my_rewrite_flush() { create_postTypeProducts(); flush_rewrite_rules(); } add_action( 'after_switch_theme', 'my_rewrite_flush' ); </code></pre> <p>Any help would be hugely appreciated. </p> <p>Thanks, </p>
[ { "answer_id": 295281, "author": "Morgan Estes", "author_id": 26317, "author_profile": "https://wordpress.stackexchange.com/users/26317", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://developer.wordpress.org/plugins/javascript/ajax/\" rel=\"nofollow noreferrer\">WordPress Plugin Developer Handbook</a> has background info and code samples of how to use Ajax in your plugin (and themes). Give it a read and it should get you on the right path.</p>\n" }, { "answer_id": 295283, "author": "Xhynk", "author_id": 13724, "author_profile": "https://wordpress.stackexchange.com/users/13724", "pm_score": 0, "selected": false, "text": "<p>Here's a very simple AJAX call on button click.</p>\n\n<p>Note the standard <strong>wp_ajax_{action_name}</strong> only fires for logged-in users. If you need to also listen for Ajax requests that don't come from logged-in users, you need to use <strong>wp_ajax_nopriv_{action_name}</strong></p>\n\n<h1>JS:</h1>\n\n<pre><code>$('body').on('click', '.your-button', function(){\n var data = {\n 'action': 'nam_nguyen_hook',\n };\n\n $.post(ajaxurl, data, function(response) {\n alert( response.message );\n }, 'json');\n});\n</code></pre>\n\n<h1>PHP:</h1>\n\n<pre><code>add_action( 'wp_ajax_nam_nguyen_hook', 'nam_nguyen_hook' );\nadd_action( 'wp_ajax_nopriv_nam_nguyen_hook', 'nam_nguyen_hook' );\n\nfunction nam_nguyen_hook() {\n $response = array();\n\n $response['status'] = 200;\n $response['message'] = 'Successfully sent an AJAX request';\n\n echo json_encode( $response );\n wp_die();\n}\n</code></pre>\n\n<p>With this, if you have an element with <code>class=\"your-button\"</code> in your admin, and click on it - you should get the \"Successfully sent an AJAX request\" message back.</p>\n\n<p>Also note you need to make sure your <code>ajax.php</code> file is being required or included. Otherwise just put that PHP in your <code>functions.php</code> file.</p>\n" } ]
2018/02/27
[ "https://wordpress.stackexchange.com/questions/295284", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108080/" ]
I'm building a custom theme using Xampp on my localhost. I've got everything sorted for the site, except for this permalinks issue. Currently, the site uses the Advanced Custom Fields plugin and has some dependencies on this plugin to work. When using plain permalinks, the site works fine. When I change to "Post name" permalinks, all pages on the site return 404 errors, except for the Custom Post Types that I've setup, which function as normal pages. I can revert back to one of the default themes, and the permalinks start working as normal, so I'm fairly confident that it's a theme issue. When I replace the functions.php file with a blank file (no php code inside), the site loads minus the styles as expected, but all the links simply refresh the page instead of attempting to navigate to any of the pages. Just to confirm a few things... * mod\_rewrite is turned on in Apache, although I've also set this up on a separate Microsoft server and IIS, so I don't think this is the issue. * I've disabled all plugins (including the advanced custom posts), and the 404 issue still occurs * The pages don't return 404's when switched to the default theme * The home page renders normally regardless of what settings I use. * I'm getting the 404.php page (that I setup) returned, and not the WordPress 404 page * I've tried adding rules to flush the rewrite rules * I've tried setting global permalink rewrite structure to /%postname% which didn't make a difference * WordPress can write to the .htaccess file. This definitely changes or is created locally when permalink settings are updated so this isn't an issue either. Below is my functions.php code which initializes the Custom Post to WordPress - this is pretty much the only thing that I can think of that must contain some sort of error, as all of the above steps that I've tried don't seem to have any effect. ``` /* Add custom post type 'Products' to Tower/NPI Theme */ add_action('init', 'create_postTypeProducts', 0 ); function create_postTypeProducts() { $labels = array( 'name' => _x( 'Products', 'Post Type General Name', 'Tower-NPI'), 'singular name' => _x( 'Product', 'Singular Name', 'Tower-NPI'), 'menu_name' => _x( 'Products', 'admin menu', 'Tower-NPI'), 'name_admin_bar' => _x( 'Products', 'add new on admin bar', 'Tower-NPI' ), 'all_items' => __( 'All Products', 'Tower-NPI' ), 'view_item' => __( 'View Products', 'Tower-NPI' ), 'add_new_item' => _x( 'Add New Product', 'Tower-NPI' ), 'add_new' => _x( 'Add Product', 'Tower-NPI' ), 'edit_item' => __( 'Edit Product', 'Tower-NPI' ), 'update_item' => __( 'Update Product', 'Tower-NPI' ), 'search_items' => __( 'Search for Products', 'Tower-NPI' ), 'not_found' => __( 'Not Found', 'Tower-NPI' ), 'not_found_in_trash' => __( 'Not found in Trash', 'Tower-NPI' ), ); $args = array( 'label' => __('Products', 'Tower-NPI'), 'description' => __('A list of products associated with the Tower/NPI Theme.', 'Tower-NPI'), 'labels' => $labels, 'supports' => array( 'title', 'editor', 'excerpt', 'revisions', 'author', 'thumbnail', 'custom-fields', 'post-formats', 'page-attributes' ), 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'show_in_nav_menus' => true, 'show_in_admin_bar' => true, 'menu_position' => 21, 'menu_icon' => 'dashicons-admin-home', 'can_export' => true, 'has_archive' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'capability_type' => 'post', 'show_in_rest' => true, 'rest_base' => 'products-api', 'rest_controller_class' => 'WP_REST_Posts_Controller', 'rewrite' => array('slug' => '/', 'with_front' => false,) ); register_post_type('Products', $args ); } /* Flush rewrite rules on theme switch */ function my_rewrite_flush() { create_postTypeProducts(); flush_rewrite_rules(); } add_action( 'after_switch_theme', 'my_rewrite_flush' ); ``` Any help would be hugely appreciated. Thanks,
The [WordPress Plugin Developer Handbook](https://developer.wordpress.org/plugins/javascript/ajax/) has background info and code samples of how to use Ajax in your plugin (and themes). Give it a read and it should get you on the right path.
295,287
<p>I have a custom code in sidebar.php that shows all my categories and number of posts+custom posts. The code is working fine but, since I copied/pasted and modified various other codes from stackexchange forum, I am wondering how efficient the code is. </p> <p>I don't have any background on php, but at least I can tell the below code is little bit messy. Especially, the code repeats almost same lines three times to show all child categories properly and count normal posts and custom posts separately. The codes shows something like</p> <p>Grandparent (100+20)</p> <ul> <li>Parent1 (20+5) <ul> <li>Child 1.1 (10+0)</li> <li>Child 1.2 (10+5) </li> </ul></li> <li>Parent 2 (80+15) <ul> <li>Child 2.1 (40+5)</li> <li>Child 2.2 (40+5)</li> <li>Child 2.3 (0+5)</li> </ul></li> </ul> <p>Is there a way to simplify the code below? and how good/bad is the code in term of speed+efficiency?</p> <pre><code>&lt;aside class="widget widget_categories"&gt; &lt;h3 class="widget-title"&gt;&lt;span class="widget-title-tab"&gt;Categories&lt;/span&gt;&lt;/h3&gt; &lt;?php $categories = get_categories( array('parent' =&gt; 0, 'hide_empty' =&gt; 0, 'orderby' =&gt; 'term_order' ) ); ?&gt; &lt;?php if($categories): ?&gt; &lt;ul&gt; &lt;?php $cat_posts = get_posts('post_type=post&amp;category=' . $cat-&gt;term_id . '&amp;numberposts=-1'); ?&gt; &lt;?php $cat_probs = get_posts('post_type=probsoln&amp;category=' . $cat-&gt;term_id . '&amp;numberposts=-1'); ?&gt; &lt;?php $count = count($cat_posts); ?&gt; &lt;?php $count_prob = count($cat_probs); ?&gt; &lt;li class="cat-item" style=""&gt;&lt;a href="&lt;?php echo get_category_link($cat-&gt;term_id); ?&gt;"&gt;&lt;?php echo $cat-&gt;name; ?&gt;&lt;/a&gt;&lt;span class="post_count"&gt;&lt;?php echo " ($count+$count_prob)"; ?&gt;&lt;/span&gt; &lt;?php $sub_categories = get_categories( array('parent' =&gt; $cat-&gt;term_id, 'hide_empty' =&gt; 0, 'orderby' =&gt; 'term_order' ) ); ?&gt; &lt;?php if($sub_categories): ?&gt; &lt;ul class="children"&gt; &lt;?php foreach ($sub_categories as $sub_cat): ?&gt; &lt;?php $sub_cat_posts = get_posts('post_type=post&amp;category=' . $sub_cat-&gt;term_id . '&amp;numberposts=-1'); ?&gt; &lt;?php $sub_cat_probs = get_posts('post_type=probsoln&amp;category=' . $sub_cat-&gt;term_id . '&amp;numberposts=-1'); ?&gt; &lt;?php $sub_count = count($sub_cat_posts); ?&gt; &lt;?php $sub_count_prob = count($sub_cat_probs); ?&gt; &lt;li class="cat-item"&gt;&lt;a href="&lt;?php echo get_category_link($sub_cat-&gt;term_id); ?&gt;"&gt;&lt;?php echo $sub_cat-&gt;name; ?&gt;&lt;/a&gt;&lt;span class="post_count"&gt;&lt;?php echo " ($sub_count+$sub_count_prob)"; ?&gt;&lt;/span&gt; &lt;?php $sub_sub_categories = get_categories( array('parent' =&gt; $sub_cat-&gt;term_id, 'hide_empty' =&gt; 0, 'orderby' =&gt; 'term_order' ) ); ?&gt; &lt;?php if($sub_sub_categories): ?&gt; &lt;ul class="children"&gt; &lt;?php foreach ($sub_sub_categories as $sub_sub_cat): ?&gt; &lt;?php $sub_sub_cat_posts = get_posts('post_type=post&amp;category=' . $sub_sub_cat-&gt;term_id . '&amp;numberposts=-1'); ?&gt; &lt;?php $sub_sub_cat_probs = get_posts('post_type=probsoln&amp;category=' . $sub_sub_cat-&gt;term_id . '&amp;numberposts=-1'); ?&gt; &lt;?php $sub_sub_count = count($sub_sub_cat_posts); ?&gt; &lt;?php $sub_sub_count_prob = count($sub_sub_cat_probs); ?&gt; &lt;li class="cat-item"&gt;&lt;a href="&lt;?php echo get_category_link($sub_sub_cat-&gt;term_id); ?&gt;"&gt;&lt;?php echo $sub_sub_cat-&gt;name; ?&gt;&lt;/a&gt;&lt;span class="post_count"&gt;&lt;?php echo " ($sub_sub_count+$sub_sub_count_prob)"; ?&gt;&lt;/span&gt; &lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; &lt;?php endif; ?&gt; &lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; &lt;?php endif; ?&gt; &lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; &lt;?php endif; ?&gt; &lt;/aside&gt; </code></pre>
[ { "answer_id": 295281, "author": "Morgan Estes", "author_id": 26317, "author_profile": "https://wordpress.stackexchange.com/users/26317", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://developer.wordpress.org/plugins/javascript/ajax/\" rel=\"nofollow noreferrer\">WordPress Plugin Developer Handbook</a> has background info and code samples of how to use Ajax in your plugin (and themes). Give it a read and it should get you on the right path.</p>\n" }, { "answer_id": 295283, "author": "Xhynk", "author_id": 13724, "author_profile": "https://wordpress.stackexchange.com/users/13724", "pm_score": 0, "selected": false, "text": "<p>Here's a very simple AJAX call on button click.</p>\n\n<p>Note the standard <strong>wp_ajax_{action_name}</strong> only fires for logged-in users. If you need to also listen for Ajax requests that don't come from logged-in users, you need to use <strong>wp_ajax_nopriv_{action_name}</strong></p>\n\n<h1>JS:</h1>\n\n<pre><code>$('body').on('click', '.your-button', function(){\n var data = {\n 'action': 'nam_nguyen_hook',\n };\n\n $.post(ajaxurl, data, function(response) {\n alert( response.message );\n }, 'json');\n});\n</code></pre>\n\n<h1>PHP:</h1>\n\n<pre><code>add_action( 'wp_ajax_nam_nguyen_hook', 'nam_nguyen_hook' );\nadd_action( 'wp_ajax_nopriv_nam_nguyen_hook', 'nam_nguyen_hook' );\n\nfunction nam_nguyen_hook() {\n $response = array();\n\n $response['status'] = 200;\n $response['message'] = 'Successfully sent an AJAX request';\n\n echo json_encode( $response );\n wp_die();\n}\n</code></pre>\n\n<p>With this, if you have an element with <code>class=\"your-button\"</code> in your admin, and click on it - you should get the \"Successfully sent an AJAX request\" message back.</p>\n\n<p>Also note you need to make sure your <code>ajax.php</code> file is being required or included. Otherwise just put that PHP in your <code>functions.php</code> file.</p>\n" } ]
2018/02/27
[ "https://wordpress.stackexchange.com/questions/295287", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137618/" ]
I have a custom code in sidebar.php that shows all my categories and number of posts+custom posts. The code is working fine but, since I copied/pasted and modified various other codes from stackexchange forum, I am wondering how efficient the code is. I don't have any background on php, but at least I can tell the below code is little bit messy. Especially, the code repeats almost same lines three times to show all child categories properly and count normal posts and custom posts separately. The codes shows something like Grandparent (100+20) * Parent1 (20+5) + Child 1.1 (10+0) + Child 1.2 (10+5) * Parent 2 (80+15) + Child 2.1 (40+5) + Child 2.2 (40+5) + Child 2.3 (0+5) Is there a way to simplify the code below? and how good/bad is the code in term of speed+efficiency? ``` <aside class="widget widget_categories"> <h3 class="widget-title"><span class="widget-title-tab">Categories</span></h3> <?php $categories = get_categories( array('parent' => 0, 'hide_empty' => 0, 'orderby' => 'term_order' ) ); ?> <?php if($categories): ?> <ul> <?php $cat_posts = get_posts('post_type=post&category=' . $cat->term_id . '&numberposts=-1'); ?> <?php $cat_probs = get_posts('post_type=probsoln&category=' . $cat->term_id . '&numberposts=-1'); ?> <?php $count = count($cat_posts); ?> <?php $count_prob = count($cat_probs); ?> <li class="cat-item" style=""><a href="<?php echo get_category_link($cat->term_id); ?>"><?php echo $cat->name; ?></a><span class="post_count"><?php echo " ($count+$count_prob)"; ?></span> <?php $sub_categories = get_categories( array('parent' => $cat->term_id, 'hide_empty' => 0, 'orderby' => 'term_order' ) ); ?> <?php if($sub_categories): ?> <ul class="children"> <?php foreach ($sub_categories as $sub_cat): ?> <?php $sub_cat_posts = get_posts('post_type=post&category=' . $sub_cat->term_id . '&numberposts=-1'); ?> <?php $sub_cat_probs = get_posts('post_type=probsoln&category=' . $sub_cat->term_id . '&numberposts=-1'); ?> <?php $sub_count = count($sub_cat_posts); ?> <?php $sub_count_prob = count($sub_cat_probs); ?> <li class="cat-item"><a href="<?php echo get_category_link($sub_cat->term_id); ?>"><?php echo $sub_cat->name; ?></a><span class="post_count"><?php echo " ($sub_count+$sub_count_prob)"; ?></span> <?php $sub_sub_categories = get_categories( array('parent' => $sub_cat->term_id, 'hide_empty' => 0, 'orderby' => 'term_order' ) ); ?> <?php if($sub_sub_categories): ?> <ul class="children"> <?php foreach ($sub_sub_categories as $sub_sub_cat): ?> <?php $sub_sub_cat_posts = get_posts('post_type=post&category=' . $sub_sub_cat->term_id . '&numberposts=-1'); ?> <?php $sub_sub_cat_probs = get_posts('post_type=probsoln&category=' . $sub_sub_cat->term_id . '&numberposts=-1'); ?> <?php $sub_sub_count = count($sub_sub_cat_posts); ?> <?php $sub_sub_count_prob = count($sub_sub_cat_probs); ?> <li class="cat-item"><a href="<?php echo get_category_link($sub_sub_cat->term_id); ?>"><?php echo $sub_sub_cat->name; ?></a><span class="post_count"><?php echo " ($sub_sub_count+$sub_sub_count_prob)"; ?></span> </li> <?php endforeach; ?> </ul> <?php endif; ?> </li> <?php endforeach; ?> </ul> <?php endif; ?> </li> <?php endforeach; ?> </ul> <?php endif; ?> </aside> ```
The [WordPress Plugin Developer Handbook](https://developer.wordpress.org/plugins/javascript/ajax/) has background info and code samples of how to use Ajax in your plugin (and themes). Give it a read and it should get you on the right path.
295,301
<p>I have successfully hidden my plugin from the plugins page using <code>$wp_list_table</code> however the pagination at the top still lists plugins as 'All (3)' etc.</p> <p>I managed to successfully alter the <code>$wp_list_table</code> array of <code>_pagination_args = total_items</code>.</p> <p>But it was still rendering Plugins - 'All (3)' at the top of the page.</p> <p>Any ideas on how I can fix this?</p> <p>I have found <code>WP_Plugins_List_Table::prepare_items()</code> has a global <code>$totals</code> variable but I am unsure of how I would change this,</p> <p>Inside this function it has</p> <pre><code>$totals = array(); foreach ( $plugins as $type =&gt; $list ) $totals[ $type ] = count( $list ); </code></pre> <p>All I am looking for is to get the total plugins number and - 1 before it renders on the page.</p>
[ { "answer_id": 295309, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 1, "selected": false, "text": "<p>The values haven't any hook to change this. However it is easy to identify the counter via Javascript. You can change this with short lines of Javascript.</p>\n\n<h2>Hook</h2>\n\n<p>You should hook in this page hook of the plugin page <code>admin_footer-plugins.php</code>, like <code>add_action( 'admin_footer-plugins.php', [ $this, 'change_view_values' ], 11 );</code></p>\n\n<h2>Function include javascript</h2>\n\n<p>As example a function below that change counter for the <code>must-use</code> count, but you should only change the selector for the plugin counter. Small hint, the php variable <code>$this-&gt;mustuse_total</code> is my store for the new count. You should replace this with your count, a function that get the count of plugins.</p>\n\n<pre><code>/**\n * Change total count for must use values\n *\n * @since 01/09/2014\n * @return void\n */\npublic function change_view_values() {\n\n $current_screen = get_current_screen();\n if ( null === $current_screen || 'plugins-network' !== $current_screen-&gt;id ) {\n return;\n }\n\n $item = sprintf( _n( 'item', 'items', $this-&gt;mustuse_total ), number_format_i18n( $this-&gt;mustuse_total ) ); ?&gt;\n\n &lt;script type=\"text/javascript\"&gt;\n jQuery( document ).ready( function($) {\n let text,\n value,\n mustuse,\n selector;\n // replace the brackets and set int value\n selector = '.mustuse span';\n text = $( selector ).text();\n value = text.replace( '(', '' );\n value = parseInt( value.replace( ')', '' ) );\n // replace and add strings\n mustuse = value + &lt;?php echo $this-&gt;mustuse_total; ?&gt;;\n $( selector ).replaceWith( '(' + mustuse + ')' );\n mustuse = mustuse + ' &lt;?php echo esc_attr( $item ); ?&gt;';\n if ( document.URL.search( /plugin_status=mustuse/ ) !== - 1 ) {\n $( '.tablenav .displaying-num' ).replaceWith( mustuse );\n }\n } );\n &lt;/script&gt;\n &lt;?php\n}\n</code></pre>\n\n<p>The code is currently in usage in this <a href=\"https://github.com/bueltge/must-use-loader/\" rel=\"nofollow noreferrer\">mu-plugin loader</a> - <a href=\"https://github.com/bueltge/must-use-loader/blob/master/must_use_loader.php#L290\" rel=\"nofollow noreferrer\">https://github.com/bueltge/must-use-loader/blob/master/must_use_loader.php#L290</a></p>\n\n<h2>Sreenshot say more</h2>\n\n<p>In my context I change the must use counter, easier to understand via the image below.\n<a href=\"https://i.stack.imgur.com/mCtLe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mCtLe.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 363248, "author": "Atik", "author_id": 185444, "author_profile": "https://wordpress.stackexchange.com/users/185444", "pm_score": 0, "selected": false, "text": "<p>It's very simple. Just add -1 to count( $list ) on third line like below:</p>\n\n<pre><code>$totals = array();\nforeach ( $plugins as $type =&gt; $list )\n $totals[ $type ] = count( $list )-1;\n</code></pre>\n" } ]
2018/02/27
[ "https://wordpress.stackexchange.com/questions/295301", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137624/" ]
I have successfully hidden my plugin from the plugins page using `$wp_list_table` however the pagination at the top still lists plugins as 'All (3)' etc. I managed to successfully alter the `$wp_list_table` array of `_pagination_args = total_items`. But it was still rendering Plugins - 'All (3)' at the top of the page. Any ideas on how I can fix this? I have found `WP_Plugins_List_Table::prepare_items()` has a global `$totals` variable but I am unsure of how I would change this, Inside this function it has ``` $totals = array(); foreach ( $plugins as $type => $list ) $totals[ $type ] = count( $list ); ``` All I am looking for is to get the total plugins number and - 1 before it renders on the page.
The values haven't any hook to change this. However it is easy to identify the counter via Javascript. You can change this with short lines of Javascript. Hook ---- You should hook in this page hook of the plugin page `admin_footer-plugins.php`, like `add_action( 'admin_footer-plugins.php', [ $this, 'change_view_values' ], 11 );` Function include javascript --------------------------- As example a function below that change counter for the `must-use` count, but you should only change the selector for the plugin counter. Small hint, the php variable `$this->mustuse_total` is my store for the new count. You should replace this with your count, a function that get the count of plugins. ``` /** * Change total count for must use values * * @since 01/09/2014 * @return void */ public function change_view_values() { $current_screen = get_current_screen(); if ( null === $current_screen || 'plugins-network' !== $current_screen->id ) { return; } $item = sprintf( _n( 'item', 'items', $this->mustuse_total ), number_format_i18n( $this->mustuse_total ) ); ?> <script type="text/javascript"> jQuery( document ).ready( function($) { let text, value, mustuse, selector; // replace the brackets and set int value selector = '.mustuse span'; text = $( selector ).text(); value = text.replace( '(', '' ); value = parseInt( value.replace( ')', '' ) ); // replace and add strings mustuse = value + <?php echo $this->mustuse_total; ?>; $( selector ).replaceWith( '(' + mustuse + ')' ); mustuse = mustuse + ' <?php echo esc_attr( $item ); ?>'; if ( document.URL.search( /plugin_status=mustuse/ ) !== - 1 ) { $( '.tablenav .displaying-num' ).replaceWith( mustuse ); } } ); </script> <?php } ``` The code is currently in usage in this [mu-plugin loader](https://github.com/bueltge/must-use-loader/) - <https://github.com/bueltge/must-use-loader/blob/master/must_use_loader.php#L290> Sreenshot say more ------------------ In my context I change the must use counter, easier to understand via the image below. [![enter image description here](https://i.stack.imgur.com/mCtLe.png)](https://i.stack.imgur.com/mCtLe.png)
295,315
<p>So I want to have a normal menu on the home page but on the other pages, I want "hamburger" menus! I've searched for a plugin but all of the menu plugins were more like to edit the mobile menu or had an absolute different purpose.So my question is does anyone have a solution for this?</p>
[ { "answer_id": 295317, "author": "Beee", "author_id": 103402, "author_profile": "https://wordpress.stackexchange.com/users/103402", "pm_score": 0, "selected": false, "text": "<p>The easiest would be to serve 2 different menus and assign them different css classes, so you can style them differently.</p>\n\n<pre><code>if ( is_home() ) {\n // use home menu\n wp_nav_menu( array( 'menu' =&gt; 'home', 'menu_class' =&gt; 'menu_home' );\n} else {\n // use other menu\n wp_nav_menu( array( 'menu' =&gt; 'nohome', 'menu_class' =&gt; 'menu_no_home' );\n}\n</code></pre>\n\n<p>I think, a plugin would make it more complicated than needed.</p>\n" }, { "answer_id": 295428, "author": "Bhavesh Taneja", "author_id": 137702, "author_profile": "https://wordpress.stackexchange.com/users/137702", "pm_score": -1, "selected": false, "text": "<p>Create New menu for other pages and add condition on header where you are displaying your main manu</p>\n\n<p>if( is_front_page() &amp;&amp; is_home() ) {\n wp_nav_menu( array(\n 'theme_location' => 'home',\n ) );\n } else { \n wp_nav_menu( array(\n 'theme_location' => 'new',\n ) );\n }</p>\n" } ]
2018/02/27
[ "https://wordpress.stackexchange.com/questions/295315", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137633/" ]
So I want to have a normal menu on the home page but on the other pages, I want "hamburger" menus! I've searched for a plugin but all of the menu plugins were more like to edit the mobile menu or had an absolute different purpose.So my question is does anyone have a solution for this?
The easiest would be to serve 2 different menus and assign them different css classes, so you can style them differently. ``` if ( is_home() ) { // use home menu wp_nav_menu( array( 'menu' => 'home', 'menu_class' => 'menu_home' ); } else { // use other menu wp_nav_menu( array( 'menu' => 'nohome', 'menu_class' => 'menu_no_home' ); } ``` I think, a plugin would make it more complicated than needed.
295,367
<p>I have created a custom taxonomy for my posts called "Regions." And I have tagged 2 posts with these regions. What I would like to do is list out any post that is tagged with a region, but for some reason it's not working. Here's my function to register the custom taxonomy:</p> <pre><code>function region_taxonomy() { $labels = array( 'name' =&gt; _x( 'Regions', 'taxonomy general name' ), 'singular_name' =&gt; _x( 'Region', 'taxonomy singular name' ), 'search_items' =&gt; __( 'Search Regions' ), 'all_items' =&gt; __( 'All Regions' ), 'parent_item' =&gt; __( 'Parent Region' ), 'parent_item_colon' =&gt; __( 'Parent Region:' ), 'edit_item' =&gt; __( 'Edit Region' ), 'update_item' =&gt; __( 'Update Region' ), 'add_new_item' =&gt; __( 'Add New Region' ), 'new_item_name' =&gt; __( 'New Region Name' ), 'menu_name' =&gt; __( 'Regions' ) ); register_taxonomy('regions',array('post'), array( 'hierarchical' =&gt; true, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'region' ) )); } add_action('init', 'region_taxonomy', 0); </code></pre> <p>And here's the <code>WP_Query</code> from my page template:</p> <pre><code>&lt;?php $args = array( 'orderby' =&gt; 'date', 'post_type' =&gt; 'post', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'regions' ), ), 'posts_per_page' =&gt; '-1' ); $the_query = new WP_Query( $args ); ?&gt; &lt;?php if ( $the_query-&gt;have_posts() ) : while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); ?&gt; &lt;?php the_content(); ?&gt; &lt;?php endwhile; else: ?&gt; &lt;p&gt;Sorry, there are no posts to display&lt;/p&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_query(); ?&gt; </code></pre> <p>Unfortunately this is returning no posts even though I have 2 posts tagged with a Region. Any ideas?</p>
[ { "answer_id": 295370, "author": "user13286", "author_id": 13286, "author_profile": "https://wordpress.stackexchange.com/users/13286", "pm_score": 0, "selected": false, "text": "<p>Apparently only specifying the <code>taxonomy</code> is not enough, I was able to solve my issue like this:</p>\n\n<pre><code>&lt;?php\n $regions_terms = get_terms('regions');\n $regions = array();\n foreach ($regions_terms as $regions_term) {\n $regions[] = $regions_term-&gt;slug;\n }\n $args = array( \n 'orderby' =&gt; 'date',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'regions',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $regions\n )\n ),\n 'posts_per_page' =&gt; '3'\n );\n $the_query = new WP_Query( $args );\n?&gt;\n</code></pre>\n" }, { "answer_id": 295371, "author": "obiPlabon", "author_id": 135737, "author_profile": "https://wordpress.stackexchange.com/users/135737", "pm_score": 3, "selected": true, "text": "<p>Taxonomy query doesn't work without <code>terms</code> parameter. So you have to first query all the <strong>regions</strong> term then assign term ids to taxonomy query.</p>\n\n<p>Here's the solution - </p>\n\n<pre><code>$terms = get_terms( array(\n 'taxonomy' =&gt; 'regions',\n 'fields' =&gt; 'id=&gt;slug',\n) );\n\n$args = array( \n 'orderby' =&gt; 'date',\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; -1,\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'regions',\n 'field' =&gt; 'term_id',\n 'terms' =&gt; array_keys( $terms ),\n ),\n ),\n);\n\n$the_query = new WP_Query( $args );\n\nif ( $the_query-&gt;have_posts() ) {\n while ( $the_query-&gt;have_posts() ) {\n $the_query-&gt;the_post();\n the_content();\n }\n wp_reset_postdata();\n} else {\n echo '&lt;p&gt;Sorry, there are no posts to display&lt;/p&gt;';\n}\n</code></pre>\n\n<p>Btw, you shouldn't use <code>wp_reset_query()</code> it's costly and should be used with <code>query_posts()</code> only instead use <code>wp_reset_postdata()</code>.</p>\n" } ]
2018/02/27
[ "https://wordpress.stackexchange.com/questions/295367", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/13286/" ]
I have created a custom taxonomy for my posts called "Regions." And I have tagged 2 posts with these regions. What I would like to do is list out any post that is tagged with a region, but for some reason it's not working. Here's my function to register the custom taxonomy: ``` function region_taxonomy() { $labels = array( 'name' => _x( 'Regions', 'taxonomy general name' ), 'singular_name' => _x( 'Region', 'taxonomy singular name' ), 'search_items' => __( 'Search Regions' ), 'all_items' => __( 'All Regions' ), 'parent_item' => __( 'Parent Region' ), 'parent_item_colon' => __( 'Parent Region:' ), 'edit_item' => __( 'Edit Region' ), 'update_item' => __( 'Update Region' ), 'add_new_item' => __( 'Add New Region' ), 'new_item_name' => __( 'New Region Name' ), 'menu_name' => __( 'Regions' ) ); register_taxonomy('regions',array('post'), array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'region' ) )); } add_action('init', 'region_taxonomy', 0); ``` And here's the `WP_Query` from my page template: ``` <?php $args = array( 'orderby' => 'date', 'post_type' => 'post', 'tax_query' => array( array( 'taxonomy' => 'regions' ), ), 'posts_per_page' => '-1' ); $the_query = new WP_Query( $args ); ?> <?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <?php the_content(); ?> <?php endwhile; else: ?> <p>Sorry, there are no posts to display</p> <?php endif; ?> <?php wp_reset_query(); ?> ``` Unfortunately this is returning no posts even though I have 2 posts tagged with a Region. Any ideas?
Taxonomy query doesn't work without `terms` parameter. So you have to first query all the **regions** term then assign term ids to taxonomy query. Here's the solution - ``` $terms = get_terms( array( 'taxonomy' => 'regions', 'fields' => 'id=>slug', ) ); $args = array( 'orderby' => 'date', 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => -1, 'tax_query' => array( array( 'taxonomy' => 'regions', 'field' => 'term_id', 'terms' => array_keys( $terms ), ), ), ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { while ( $the_query->have_posts() ) { $the_query->the_post(); the_content(); } wp_reset_postdata(); } else { echo '<p>Sorry, there are no posts to display</p>'; } ``` Btw, you shouldn't use `wp_reset_query()` it's costly and should be used with `query_posts()` only instead use `wp_reset_postdata()`.
295,373
<p>I am using WordPress's default Gallery and adding categories to them. I now created a shortcode with a loop to get the Galleries to a page:</p> <pre><code>if(! function_exists('test_shortcode')){ function lv_gallery_style_one_shortcode($atts, $content = null){ extract(shortcode_atts( array( 'title'=&gt;'', ), $atts) ); $port=array('post_type' =&gt; 'gallery', 'category_name' =&gt; 'beach', 'showposts' =&gt; -1 ); $loop=new WP_Query($port); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); // HERE IS THE LOOP return $html; } add_shortcode('gallery_test', 'test_shortcode' ); </code></pre> <p>I know that the loop worked just fine because when I remove <code>'category_name' =&gt; 'beach'</code> it displays all the categories.</p> <p>---------------<strong>EDIT:</strong>-----------------</p> <p>The Gallery I am using has the following icon and option:</p> <p><a href="https://i.stack.imgur.com/S24mv.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/S24mv.jpg" alt="enter image description here"></a></p> <p>I thought this is the standard WP gallery, am I wrong?</p> <p>When I create a new Gallery, there is a Category section on the right side:</p> <p><a href="https://i.stack.imgur.com/lLjI9.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/lLjI9.jpg" alt="Category section"></a></p> <p>What is this used for if I cannot use them? I don't understand.</p> <p>---------------<strong>End EDIT:</strong>-------------</p> <p>This is just an example code. In the complete version, the category name will be a parameter to enter in the shortcode, that is why I would like to do it like this.</p> <p>Any ideas on how to get this to work?</p> <p>Any suggestions are appreciated :).</p> <p>Thanks.</p>
[ { "answer_id": 295370, "author": "user13286", "author_id": 13286, "author_profile": "https://wordpress.stackexchange.com/users/13286", "pm_score": 0, "selected": false, "text": "<p>Apparently only specifying the <code>taxonomy</code> is not enough, I was able to solve my issue like this:</p>\n\n<pre><code>&lt;?php\n $regions_terms = get_terms('regions');\n $regions = array();\n foreach ($regions_terms as $regions_term) {\n $regions[] = $regions_term-&gt;slug;\n }\n $args = array( \n 'orderby' =&gt; 'date',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'regions',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $regions\n )\n ),\n 'posts_per_page' =&gt; '3'\n );\n $the_query = new WP_Query( $args );\n?&gt;\n</code></pre>\n" }, { "answer_id": 295371, "author": "obiPlabon", "author_id": 135737, "author_profile": "https://wordpress.stackexchange.com/users/135737", "pm_score": 3, "selected": true, "text": "<p>Taxonomy query doesn't work without <code>terms</code> parameter. So you have to first query all the <strong>regions</strong> term then assign term ids to taxonomy query.</p>\n\n<p>Here's the solution - </p>\n\n<pre><code>$terms = get_terms( array(\n 'taxonomy' =&gt; 'regions',\n 'fields' =&gt; 'id=&gt;slug',\n) );\n\n$args = array( \n 'orderby' =&gt; 'date',\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; -1,\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'regions',\n 'field' =&gt; 'term_id',\n 'terms' =&gt; array_keys( $terms ),\n ),\n ),\n);\n\n$the_query = new WP_Query( $args );\n\nif ( $the_query-&gt;have_posts() ) {\n while ( $the_query-&gt;have_posts() ) {\n $the_query-&gt;the_post();\n the_content();\n }\n wp_reset_postdata();\n} else {\n echo '&lt;p&gt;Sorry, there are no posts to display&lt;/p&gt;';\n}\n</code></pre>\n\n<p>Btw, you shouldn't use <code>wp_reset_query()</code> it's costly and should be used with <code>query_posts()</code> only instead use <code>wp_reset_postdata()</code>.</p>\n" } ]
2018/02/27
[ "https://wordpress.stackexchange.com/questions/295373", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71410/" ]
I am using WordPress's default Gallery and adding categories to them. I now created a shortcode with a loop to get the Galleries to a page: ``` if(! function_exists('test_shortcode')){ function lv_gallery_style_one_shortcode($atts, $content = null){ extract(shortcode_atts( array( 'title'=>'', ), $atts) ); $port=array('post_type' => 'gallery', 'category_name' => 'beach', 'showposts' => -1 ); $loop=new WP_Query($port); while ( $loop->have_posts() ) : $loop->the_post(); // HERE IS THE LOOP return $html; } add_shortcode('gallery_test', 'test_shortcode' ); ``` I know that the loop worked just fine because when I remove `'category_name' => 'beach'` it displays all the categories. ---------------**EDIT:**----------------- The Gallery I am using has the following icon and option: [![enter image description here](https://i.stack.imgur.com/S24mv.jpg)](https://i.stack.imgur.com/S24mv.jpg) I thought this is the standard WP gallery, am I wrong? When I create a new Gallery, there is a Category section on the right side: [![Category section](https://i.stack.imgur.com/lLjI9.jpg)](https://i.stack.imgur.com/lLjI9.jpg) What is this used for if I cannot use them? I don't understand. ---------------**End EDIT:**------------- This is just an example code. In the complete version, the category name will be a parameter to enter in the shortcode, that is why I would like to do it like this. Any ideas on how to get this to work? Any suggestions are appreciated :). Thanks.
Taxonomy query doesn't work without `terms` parameter. So you have to first query all the **regions** term then assign term ids to taxonomy query. Here's the solution - ``` $terms = get_terms( array( 'taxonomy' => 'regions', 'fields' => 'id=>slug', ) ); $args = array( 'orderby' => 'date', 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => -1, 'tax_query' => array( array( 'taxonomy' => 'regions', 'field' => 'term_id', 'terms' => array_keys( $terms ), ), ), ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { while ( $the_query->have_posts() ) { $the_query->the_post(); the_content(); } wp_reset_postdata(); } else { echo '<p>Sorry, there are no posts to display</p>'; } ``` Btw, you shouldn't use `wp_reset_query()` it's costly and should be used with `query_posts()` only instead use `wp_reset_postdata()`.
295,405
<p>I have created a custom Plugin, and wanted to hide its shortcode <code>[related]</code> from the content once the plugin is deactivated. Everything is working fine, but when i deactivate the plugin the stray shortcode is still there. and i dont want to install any other plugin to hide that.</p> <pre><code>register_deactivation_hook( __FILE__ , array($relatedPost, 'deactivated')); class RelatedPost { function deactivated(){ // flush rewrite rules flush_rewrite_rules(); } } </code></pre>
[ { "answer_id": 295410, "author": "Iceable", "author_id": 136263, "author_profile": "https://wordpress.stackexchange.com/users/136263", "pm_score": 2, "selected": false, "text": "<p>I'm afraid hiding the shortcode once the plugin is deactivated is simply not possible.</p>\n\n<p>The only way to \"hide\" a shortcode from the content is to register the shortcode with a calback that returns nothing, as in:</p>\n\n<pre><code>add_shortcode( 'related', function(){ return null; } );\n</code></pre>\n\n<p>But of course you cannot do that without an active plugin.</p>\n\n<p>Technically you <em>could</em> remove every occurence of the shortcode by pulling and editing all of the content that may contain it - but that would probably be a very bad idea, and this wouldn't allow to get them back in case the plugin is reactivated.</p>\n" }, { "answer_id": 295412, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 0, "selected": false, "text": "<p>Following code will wrap <code>[related]</code> in HTML comment tags like <code>&lt;!-- [related] --&gt;</code> on plugin deactivation.</p>\n\n<pre><code>&lt;?php\n// on plugin activation\nregister_activation_hook( __FILE__, 'my_hide_shortcut' );\n\nfunction my_hide_shortcut()\n{\n $to_find = '[related]';\n $to_replace_with ='&lt;!-- [related] --&gt;';\n\n // get MySQL table prefix\n global $wpdb;\n $table_prefix = $wpdb-&gt;prefix;\n\n // run MySQL query\n $mysql = \"UPDATE '{$table_prefix}_posts' SET 'post_content' = replace('post_content', '{$to_find}', '{$to_replace_with}')\";\n}\n</code></pre>\n\n<p>You can go further and do the opposite replace when plugin is activated again, or completely remove the shortcode on plugin uninstallation.</p>\n\n<p>This code is not tested and was posted here only to suggest an idea!\nMake the database backup before you try.\nCheck <code>$mysql</code> variable syntax. Also, may be you'll want to do MySQL stuff in WordPress way.</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/register_activation_hook/\" rel=\"nofollow noreferrer\">register_activation_hook</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/register_deactivation_hook/\" rel=\"nofollow noreferrer\">register_deactivation_hook</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/register_uninstall_hook/\" rel=\"nofollow noreferrer\">register_uninstall_hook</a></li>\n</ul>\n" } ]
2018/02/28
[ "https://wordpress.stackexchange.com/questions/295405", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126760/" ]
I have created a custom Plugin, and wanted to hide its shortcode `[related]` from the content once the plugin is deactivated. Everything is working fine, but when i deactivate the plugin the stray shortcode is still there. and i dont want to install any other plugin to hide that. ``` register_deactivation_hook( __FILE__ , array($relatedPost, 'deactivated')); class RelatedPost { function deactivated(){ // flush rewrite rules flush_rewrite_rules(); } } ```
I'm afraid hiding the shortcode once the plugin is deactivated is simply not possible. The only way to "hide" a shortcode from the content is to register the shortcode with a calback that returns nothing, as in: ``` add_shortcode( 'related', function(){ return null; } ); ``` But of course you cannot do that without an active plugin. Technically you *could* remove every occurence of the shortcode by pulling and editing all of the content that may contain it - but that would probably be a very bad idea, and this wouldn't allow to get them back in case the plugin is reactivated.
295,413
<p>I have developed a WordPress Website. It's on the live server but in development mode.I want if someone to visit my website. It should ask for password or access token to before loading site.</p> <p>Is there a way to achieve this functionality. </p> <p>Note: I have put my code in the answer that's working. Please review it. Is this the good way or there is any better way to do this. </p> <p>Thanks.</p>
[ { "answer_id": 295410, "author": "Iceable", "author_id": 136263, "author_profile": "https://wordpress.stackexchange.com/users/136263", "pm_score": 2, "selected": false, "text": "<p>I'm afraid hiding the shortcode once the plugin is deactivated is simply not possible.</p>\n\n<p>The only way to \"hide\" a shortcode from the content is to register the shortcode with a calback that returns nothing, as in:</p>\n\n<pre><code>add_shortcode( 'related', function(){ return null; } );\n</code></pre>\n\n<p>But of course you cannot do that without an active plugin.</p>\n\n<p>Technically you <em>could</em> remove every occurence of the shortcode by pulling and editing all of the content that may contain it - but that would probably be a very bad idea, and this wouldn't allow to get them back in case the plugin is reactivated.</p>\n" }, { "answer_id": 295412, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 0, "selected": false, "text": "<p>Following code will wrap <code>[related]</code> in HTML comment tags like <code>&lt;!-- [related] --&gt;</code> on plugin deactivation.</p>\n\n<pre><code>&lt;?php\n// on plugin activation\nregister_activation_hook( __FILE__, 'my_hide_shortcut' );\n\nfunction my_hide_shortcut()\n{\n $to_find = '[related]';\n $to_replace_with ='&lt;!-- [related] --&gt;';\n\n // get MySQL table prefix\n global $wpdb;\n $table_prefix = $wpdb-&gt;prefix;\n\n // run MySQL query\n $mysql = \"UPDATE '{$table_prefix}_posts' SET 'post_content' = replace('post_content', '{$to_find}', '{$to_replace_with}')\";\n}\n</code></pre>\n\n<p>You can go further and do the opposite replace when plugin is activated again, or completely remove the shortcode on plugin uninstallation.</p>\n\n<p>This code is not tested and was posted here only to suggest an idea!\nMake the database backup before you try.\nCheck <code>$mysql</code> variable syntax. Also, may be you'll want to do MySQL stuff in WordPress way.</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/register_activation_hook/\" rel=\"nofollow noreferrer\">register_activation_hook</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/register_deactivation_hook/\" rel=\"nofollow noreferrer\">register_deactivation_hook</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/register_uninstall_hook/\" rel=\"nofollow noreferrer\">register_uninstall_hook</a></li>\n</ul>\n" } ]
2018/02/28
[ "https://wordpress.stackexchange.com/questions/295413", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137328/" ]
I have developed a WordPress Website. It's on the live server but in development mode.I want if someone to visit my website. It should ask for password or access token to before loading site. Is there a way to achieve this functionality. Note: I have put my code in the answer that's working. Please review it. Is this the good way or there is any better way to do this. Thanks.
I'm afraid hiding the shortcode once the plugin is deactivated is simply not possible. The only way to "hide" a shortcode from the content is to register the shortcode with a calback that returns nothing, as in: ``` add_shortcode( 'related', function(){ return null; } ); ``` But of course you cannot do that without an active plugin. Technically you *could* remove every occurence of the shortcode by pulling and editing all of the content that may contain it - but that would probably be a very bad idea, and this wouldn't allow to get them back in case the plugin is reactivated.
295,415
<p>I would like to change the output of posts_nav_link(); ( Or be pointed in a new direction, that's fine by me ) What i want to do is show &lt; Previous archivepage| Next archivepage > even if there is no previous or next page, currently it removed whichever link isn't in use, i would like it to still show the text &lt; previous, so i can style it in a lighter grey tone ( disabled ) Hope this makes sense.</p> <p>I've tried creating custom page nav for my archive pages but it wont work..</p> <pre><code> &lt;h1&gt;custom loop&lt;/h1&gt; &lt;/div&gt; &lt;div class="col-md-12"&gt; &lt;?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type'=&gt;'post', // Your post type name 'posts_per_page' =&gt; 6, 'paged' =&gt; $paged, ); $loop = new WP_Query( $args ); if ( $loop-&gt;have_posts() ) { while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); // YOUR CODE the_id(); echo '&lt;br/&gt;'; endwhile; ?&gt; &lt;div class="navigation"&gt;&lt;p&gt;&lt;?php posts_nav_link(); ?&gt;&lt;/p&gt;&lt;/div&gt; </code></pre> <p></p> <p>Desired output:</p> <pre><code>&lt; Previous archivepage | Next archivepage &gt; </code></pre>
[ { "answer_id": 295423, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p><code>posts_nav_link()</code> just outputs <code>get_previous_posts_link()</code> and <code>get_next_posts_link()</code> with a separator between them. The helpful thing is does is handle the visibility of the separator depending on whether both pages exist. Since you always want to show something on either side, you don't need it. What you can do is output the next and previous links manually, but with a check to see of there is a link. If there isn't you can output a span instead.</p>\n\n<p>That would look like this:</p>\n\n<pre><code>if ( get_previous_posts_link() ){\n previous_posts_link( 'Previous' );\n} else {\n echo '&lt;span aria-hidden=\"true\"&gt;Previous&lt;/span&gt;';\n}\n\necho '|';\n\nif ( get_next_posts_link() ){\n next_posts_link( 'Next' );\n} else {\n echo '&lt;span aria-hidden=\"true\"&gt;Next&lt;/span&gt;';\n}\n</code></pre>\n\n<p>Now you can style <code>&lt;span&gt;</code> as the inactive link.</p>\n\n<p>Note that I've used <code>aria-hidden=\"true\"</code> to tell screen readers to ignore the text of the inactive 'links' as an accessibility featured. </p>\n" }, { "answer_id": 295426, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"https://codex.wordpress.org/Function_Reference/posts_nav_link\" rel=\"nofollow noreferrer\"><code>posts_nav_link()</code></a> function accepts 3 arguments.</p>\n\n<pre><code>&lt;?php posts_nav_link( $sep, $prelabel, $nextlabel ); ?&gt; \n</code></pre>\n\n<p>You can set the <code>$sep</code> to <code>'|'</code> and change the next and previous labels. There's no need to output back and forth navigation separately.</p>\n" } ]
2018/02/28
[ "https://wordpress.stackexchange.com/questions/295415", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108736/" ]
I would like to change the output of posts\_nav\_link(); ( Or be pointed in a new direction, that's fine by me ) What i want to do is show < Previous archivepage| Next archivepage > even if there is no previous or next page, currently it removed whichever link isn't in use, i would like it to still show the text < previous, so i can style it in a lighter grey tone ( disabled ) Hope this makes sense. I've tried creating custom page nav for my archive pages but it wont work.. ``` <h1>custom loop</h1> </div> <div class="col-md-12"> <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type'=>'post', // Your post type name 'posts_per_page' => 6, 'paged' => $paged, ); $loop = new WP_Query( $args ); if ( $loop->have_posts() ) { while ( $loop->have_posts() ) : $loop->the_post(); // YOUR CODE the_id(); echo '<br/>'; endwhile; ?> <div class="navigation"><p><?php posts_nav_link(); ?></p></div> ``` Desired output: ``` < Previous archivepage | Next archivepage > ```
`posts_nav_link()` just outputs `get_previous_posts_link()` and `get_next_posts_link()` with a separator between them. The helpful thing is does is handle the visibility of the separator depending on whether both pages exist. Since you always want to show something on either side, you don't need it. What you can do is output the next and previous links manually, but with a check to see of there is a link. If there isn't you can output a span instead. That would look like this: ``` if ( get_previous_posts_link() ){ previous_posts_link( 'Previous' ); } else { echo '<span aria-hidden="true">Previous</span>'; } echo '|'; if ( get_next_posts_link() ){ next_posts_link( 'Next' ); } else { echo '<span aria-hidden="true">Next</span>'; } ``` Now you can style `<span>` as the inactive link. Note that I've used `aria-hidden="true"` to tell screen readers to ignore the text of the inactive 'links' as an accessibility featured.
295,419
<p>I tried to place HTML code in WordPress menu description, it's showing an inline code <code>&lt;i class="fa fa-cloud"&gt;&lt;/i&gt;</code> instead of an icon.</p> <p>Already tried that one but still not working</p> <pre><code>// Allow HTML descriptions in WordPress Menu remove_filter( 'nav_menu_description', 'strip_tags' ); add_filter( 'wp_setup_nav_menu_item', 'cus_wp_setup_nav_menu_item' ); function cus_wp_setup_nav_menu_item( $menu_item ) { $menu_item-&gt;description = apply_filters( 'nav_menu_description', $menu_item-&gt;post_content ); return $menu_item; } </code></pre>
[ { "answer_id": 295422, "author": "Md. Amanur Rahman", "author_id": 109213, "author_profile": "https://wordpress.stackexchange.com/users/109213", "pm_score": -1, "selected": true, "text": "<p>Put the below full code and that should work..</p>\n\n<pre><code>&lt;?php class Description_Walker extends Walker_Nav_Menu {\n\n function start_el(&amp;$output, $item, $depth, $args)\n {\n $classes = empty ( $item-&gt;classes ) ? array () : (array) $item-&gt;classes;\n\n $class_names = join(\n ' '\n , apply_filters(\n 'nav_menu_css_class'\n , array_filter( $classes ), $item\n )\n );\n\n ! empty ( $class_names )\n and $class_names = ' class=\"'. esc_attr( $class_names ) . '\"';\n\n // Build default menu items\n $output .= \"&lt;li id='menu-item-$item-&gt;ID' $class_names&gt;\";\n\n $attributes = '';\n\n ! empty( $item-&gt;attr_title )\n and $attributes .= ' title=\"' . esc_attr( $item-&gt;attr_title ) .'\"';\n ! empty( $item-&gt;target )\n and $attributes .= ' target=\"' . esc_attr( $item-&gt;target ) .'\"';\n ! empty( $item-&gt;xfn )\n and $attributes .= ' rel=\"' . esc_attr( $item-&gt;xfn ) .'\"';\n ! empty( $item-&gt;url )\n and $attributes .= ' href=\"' . esc_attr( $item-&gt;url ) .'\"';\n\n // Build the description (you may need to change the depth to 0, 1, or 2)\n $description = ( ! empty ( $item-&gt;description ) and 1 == $depth )\n ? '&lt;span class=\"nav_desc\"&gt;'. $item-&gt;description . '&lt;/span&gt;' : '';\n\n $title = apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID );\n\n $item_output = $args-&gt;before\n . \"&lt;a $attributes&gt;\"\n . $args-&gt;link_before\n . $title\n . '&lt;/a&gt; '\n . $args-&gt;link_after\n . $description\n . $args-&gt;after;\n\n // Since $output is called by reference we don't need to return anything.\n $output .= apply_filters(\n 'walker_nav_menu_start_el'\n , $item_output\n , $item\n , $depth\n , $args\n );\n }\n}\n\n// Allow HTML descriptions in WordPress Menu\nremove_filter( 'nav_menu_description', 'strip_tags' );\nadd_filter( 'wp_setup_nav_menu_item', 'cus_wp_setup_nav_menu_item' );\nfunction cus_wp_setup_nav_menu_item( $menu_item ) {\n $menu_item-&gt;description = apply_filters( 'nav_menu_description', $menu_item-&gt;post_content );\n return $menu_item;\n} ?&gt;\n</code></pre>\n\n<p>and then use this in your template:</p>\n\n<pre><code>&lt;?php wp_nav_menu( array( 'walker' =&gt; new Description_Walker )); ?&gt;\n</code></pre>\n" }, { "answer_id": 295433, "author": "thosetinydreams", "author_id": 92750, "author_profile": "https://wordpress.stackexchange.com/users/92750", "pm_score": 1, "selected": false, "text": "<p>This is not directly solving the HTML issue, but alternatively, you could add the Font Awesome icons to the descriptions through CSS, within the <code>:before</code> pseudo element.</p>\n\n<p>Something in the lines of:</p>\n\n<pre><code>.description:before {\n content: '\\f0c2';\n font-family: FontAwesome;\n position: absolute;\n ...\n}\n</code></pre>\n\n<p>If you need a different icon for each item's descriptions, you can either use the <code>:nth-child(n)</code> selector, or the IDs of the menu items (e.g. <code>#menu-item-85 .description</code>).</p>\n" } ]
2018/02/28
[ "https://wordpress.stackexchange.com/questions/295419", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24762/" ]
I tried to place HTML code in WordPress menu description, it's showing an inline code `<i class="fa fa-cloud"></i>` instead of an icon. Already tried that one but still not working ``` // Allow HTML descriptions in WordPress Menu remove_filter( 'nav_menu_description', 'strip_tags' ); add_filter( 'wp_setup_nav_menu_item', 'cus_wp_setup_nav_menu_item' ); function cus_wp_setup_nav_menu_item( $menu_item ) { $menu_item->description = apply_filters( 'nav_menu_description', $menu_item->post_content ); return $menu_item; } ```
Put the below full code and that should work.. ``` <?php class Description_Walker extends Walker_Nav_Menu { function start_el(&$output, $item, $depth, $args) { $classes = empty ( $item->classes ) ? array () : (array) $item->classes; $class_names = join( ' ' , apply_filters( 'nav_menu_css_class' , array_filter( $classes ), $item ) ); ! empty ( $class_names ) and $class_names = ' class="'. esc_attr( $class_names ) . '"'; // Build default menu items $output .= "<li id='menu-item-$item->ID' $class_names>"; $attributes = ''; ! empty( $item->attr_title ) and $attributes .= ' title="' . esc_attr( $item->attr_title ) .'"'; ! empty( $item->target ) and $attributes .= ' target="' . esc_attr( $item->target ) .'"'; ! empty( $item->xfn ) and $attributes .= ' rel="' . esc_attr( $item->xfn ) .'"'; ! empty( $item->url ) and $attributes .= ' href="' . esc_attr( $item->url ) .'"'; // Build the description (you may need to change the depth to 0, 1, or 2) $description = ( ! empty ( $item->description ) and 1 == $depth ) ? '<span class="nav_desc">'. $item->description . '</span>' : ''; $title = apply_filters( 'the_title', $item->title, $item->ID ); $item_output = $args->before . "<a $attributes>" . $args->link_before . $title . '</a> ' . $args->link_after . $description . $args->after; // Since $output is called by reference we don't need to return anything. $output .= apply_filters( 'walker_nav_menu_start_el' , $item_output , $item , $depth , $args ); } } // Allow HTML descriptions in WordPress Menu remove_filter( 'nav_menu_description', 'strip_tags' ); add_filter( 'wp_setup_nav_menu_item', 'cus_wp_setup_nav_menu_item' ); function cus_wp_setup_nav_menu_item( $menu_item ) { $menu_item->description = apply_filters( 'nav_menu_description', $menu_item->post_content ); return $menu_item; } ?> ``` and then use this in your template: ``` <?php wp_nav_menu( array( 'walker' => new Description_Walker )); ?> ```
295,436
<p>I would like to check a posts status, in particular I want to know if a post is set to draft or is privately published.</p> <p>I have the following code:</p> <pre><code> if ('draft' != get_post_status() || is_user_logged_in()) { $this-&gt;render(); } else { wp_redirect( site_url('404') ); exit; } </code></pre> <p>It checks to see if a posts status is not set to draft or it checks if they are logged in and then renders either the post or redirects to the 404 page.</p> <p>For some reason privately published posts are visible to non logged in users and I am trying to fix this. </p>
[ { "answer_id": 295437, "author": "Christine Cooper", "author_id": 24875, "author_profile": "https://wordpress.stackexchange.com/users/24875", "pm_score": 4, "selected": true, "text": "<p>To check post with post status <code>private</code>, you could run the following:</p>\n\n<pre><code>if (get_post_status() == 'private' &amp;&amp; is_user_logged_in()) {\n // it's private and user is logged in, do stuff\n} elseif (get_post_status() == 'draft') {\n // it's draft, do stuff\n} else {\n // it's something else, do stuff\n}\n</code></pre>\n\n<p>Or, in your current setup, you can simply only display <em>published</em> posts via:</p>\n\n<pre><code>if (get_post_status() == 'publish') {\n // it's published, do stuff\n $this-&gt;render();\n}\n</code></pre>\n\n<p>You can learn more about post statuses via the <a href=\"https://codex.wordpress.org/Post_Status\" rel=\"nofollow noreferrer\">codex page</a>.</p>\n" }, { "answer_id": 295440, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 1, "selected": false, "text": "<p>I think the problem is with you logic. <code>||</code> means if any of the condition is satisfied it'll render, specially if the first condition gets satisfied it'll not check the second one anymore. So your code will be like below-</p>\n\n<pre><code>if( !is_user_logged_in() ) {\n return; // or do whatever you want to do if the user isn't logged in.\n\n // Or these below things \n\n // wp_redirect( site_url('404') );\n // exit;\n}\n\nif ( 'private' === get_post_status()) {\n // Only render private posts.\n $this-&gt;render();\n} else {\n wp_redirect( site_url('404') );\n exit;\n}\n</code></pre>\n\n<p>So, what we have done above here is, first we checked if the user is logged in or not. If not logged in we are returning it from there. It's no reaching the next if condition. This way you can prevent non-logged in user from seeing this post. In you code some how the first condition gets satisfied and <code>if</code> isn't checking the next condition. So non-logged in users are able to see your post. Now in second <code>if</code> block we are checking the post status. If the post has <code>private</code> status only then it'll be rendered. Other wise it'll be redirected.</p>\n\n<blockquote>\n <p>Anyway, some little suggestions, use <code>!==</code> rather than <code>!=</code> and <code>===</code> rather than <code>==</code>. These checks types also and makes it strictly checked. See my code, I used these.</p>\n</blockquote>\n\n<p>Hope this above helps.</p>\n" } ]
2018/02/28
[ "https://wordpress.stackexchange.com/questions/295436", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38592/" ]
I would like to check a posts status, in particular I want to know if a post is set to draft or is privately published. I have the following code: ``` if ('draft' != get_post_status() || is_user_logged_in()) { $this->render(); } else { wp_redirect( site_url('404') ); exit; } ``` It checks to see if a posts status is not set to draft or it checks if they are logged in and then renders either the post or redirects to the 404 page. For some reason privately published posts are visible to non logged in users and I am trying to fix this.
To check post with post status `private`, you could run the following: ``` if (get_post_status() == 'private' && is_user_logged_in()) { // it's private and user is logged in, do stuff } elseif (get_post_status() == 'draft') { // it's draft, do stuff } else { // it's something else, do stuff } ``` Or, in your current setup, you can simply only display *published* posts via: ``` if (get_post_status() == 'publish') { // it's published, do stuff $this->render(); } ``` You can learn more about post statuses via the [codex page](https://codex.wordpress.org/Post_Status).
295,471
<p><strong>For those that arrive from Google: You <a href="https://github.com/WP-API/docs/pull/20#issuecomment-370286436" rel="noreferrer">probably shouldn't get the nonces from the REST API</a>, unless you <em>really</em> know what you're doing. Cookie-based authentication with the REST API is only <em>meant</em> for plugins and themes. For a single page application, you should probably use <a href="https://wordpress.org/plugins/oauth2-provider/" rel="noreferrer">OAuth</a>.</strong></p> <p>This question exists because the documentation isn't/wasn't clear on how should you actually authenticate when building single page apps, JWTs aren't really fit for web apps, and OAuth is harder to implement than cookie based auth.</p> <hr> <p><a href="https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/" rel="noreferrer">The handbook</a> has an example on how the Backbone JavaScript client handles nonces, and if I follow the example, I get a nonce that the built in endpoints such as /wp/v2/posts accepts.</p> <pre><code>\wp_localize_script("client-js", "theme", [ 'nonce' =&gt; wp_create_nonce('wp_rest'), 'user' =&gt; get_current_user_id(), ]); </code></pre> <p>However, using Backbone is out of the question, and so are themes, so I wrote the following plugin: </p> <pre><code>&lt;?php /* Plugin Name: Nonce Endpoint */ add_action('rest_api_init', function () { $user = get_current_user_id(); register_rest_route('nonce/v1', 'get', [ 'methods' =&gt; 'GET', 'callback' =&gt; function () use ($user) { return [ 'nonce' =&gt; wp_create_nonce('wp_rest'), 'user' =&gt; $user, ]; }, ]); register_rest_route('nonce/v1', 'verify', [ 'methods' =&gt; 'GET', 'callback' =&gt; function () use ($user) { $nonce = !empty($_GET['nonce']) ? $_GET['nonce'] : false; return [ 'valid' =&gt; (bool) wp_verify_nonce($nonce, 'wp_rest'), 'user' =&gt; $user, ]; }, ]); }); </code></pre> <p>I tinkered in the JavaScript console a bit, and wrote the following: </p> <pre><code>var main = async () =&gt; { // var because it can be redefined const nonceReq = await fetch('/wp-json/nonce/v1/get', { credentials: 'include' }) const nonceResp = await nonceReq.json() const nonceValidReq = await fetch(`/wp-json/nonce/v1/verify?nonce=${nonceResp.nonce}`, { credentials: 'include' }) const nonceValidResp = await nonceValidReq.json() const addPost = (nonce) =&gt; fetch('/wp-json/wp/v2/posts', { method: 'POST', credentials: 'include', body: JSON.stringify({ title: `Test ${Date.now()}`, content: 'Test', }), headers: { 'X-WP-Nonce': nonce, 'content-type': 'application/json' }, }).then(r =&gt; r.json()).then(console.log) console.log(nonceResp.nonce, nonceResp.user, nonceValidResp) console.log(theme.nonce, theme.user) addPost(nonceResp.nonce) addPost(theme.nonce) } main() </code></pre> <p>The expected result is two new posts, but I get <code>Cookie nonce is invalid</code> from the first one, and the second one creates the post succesfully. That's probably because the nonces are different, but why? I'm logged in as the same user in both requests.</p> <p><a href="https://i.stack.imgur.com/aSif2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aSif2.png" alt="enter image description here"></a></p> <p>If my approach is wrong, how should I get the nonce? </p> <p><strong>Edit</strong>:</p> <p>I tried messing with globals <strike>without much luck</strike>. Got a bit luckier by utilizing wp_loaded action: </p> <pre><code>&lt;?php /* Plugin Name: Nonce Endpoint */ $nonce = 'invalid'; add_action('wp_loaded', function () { global $nonce; $nonce = wp_create_nonce('wp_rest'); }); add_action('rest_api_init', function () { $user = get_current_user_id(); register_rest_route('nonce/v1', 'get', [ 'methods' =&gt; 'GET', 'callback' =&gt; function () use ($user) { return [ 'nonce' =&gt; $GLOBALS['nonce'], 'user' =&gt; $user, ]; }, ]); register_rest_route('nonce/v1', 'verify', [ 'methods' =&gt; 'GET', 'callback' =&gt; function () use ($user) { $nonce = !empty($_GET['nonce']) ? $_GET['nonce'] : false; error_log("verify $nonce $user"); return [ 'valid' =&gt; (bool) wp_verify_nonce($nonce, 'wp_rest'), 'user' =&gt; $user, ]; }, ]); }); </code></pre> <p>Now when I run the JavaScript above, two posts get created, but the verify endpoint fails! </p> <p><a href="https://i.stack.imgur.com/P6zzL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/P6zzL.png" alt="enter image description here"></a></p> <p>I went to debug wp_verify_nonce: </p> <pre><code>function wp_verify_nonce( $nonce, $action = -1 ) { $nonce = (string) $nonce; $user = wp_get_current_user(); $uid = (int) $user-&gt;ID; // This is 0, even though the verify endpoint says I'm logged in as user 2! </code></pre> <p>I added some logging</p> <pre><code>// Nonce generated 0-12 hours ago $expected = substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), -12, 10 ); error_log("expected 1 $expected received $nonce uid $uid action $action"); if ( hash_equals( $expected, $nonce ) ) { return 1; } // Nonce generated 12-24 hours ago $expected = substr( wp_hash( ( $i - 1 ) . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 ); error_log("expected 2 $expected received $nonce uid $uid action $action"); if ( hash_equals( $expected, $nonce ) ) { return 2; } </code></pre> <p>and the JavaScript code now results in the following entries. As you can see, when the verify endpoint is called, uid is 0.</p> <pre><code>[01-Mar-2018 11:41:57 UTC] verify 716087f772 2 [01-Mar-2018 11:41:57 UTC] expected 1 b35fa18521 received 716087f772 uid 0 action wp_rest [01-Mar-2018 11:41:57 UTC] expected 2 dd35d95cbd received 716087f772 uid 0 action wp_rest [01-Mar-2018 11:41:58 UTC] expected 1 716087f772 received 716087f772 uid 2 action wp_rest [01-Mar-2018 11:41:58 UTC] expected 1 716087f772 received 716087f772 uid 2 action wp_rest </code></pre>
[ { "answer_id": 295538, "author": "Christian", "author_id": 78685, "author_profile": "https://wordpress.stackexchange.com/users/78685", "pm_score": 1, "selected": false, "text": "<p>While this solution works, <a href=\"https://github.com/WP-API/docs/pull/20#issuecomment-370286436\" rel=\"nofollow noreferrer\">it isn't recommended</a>. OAuth is the preferred choice.</p>\n\n<hr>\n\n<p>I think I got it. </p>\n\n<p><strike>I <em>think</em> that wp_verify_nonce is broken, as wp_get_current_user fails to get the proper user object.</strike></p>\n\n<p>It isn't, as illustrated by Otto.</p>\n\n<p>Luckily it has a filter: <code>$uid = apply_filters( 'nonce_user_logged_out', $uid, $action );</code></p>\n\n<p>Using this filter I was able to write the following, and the JavaScript code executes like it should:</p>\n\n<p><a href=\"https://i.stack.imgur.com/c7orf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/c7orf.png\" alt=\"enter image description here\"></a></p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: Nonce Endpoint\n*/\n\n$nonce = 'invalid';\nadd_action('wp_loaded', function () {\n global $nonce;\n $nonce = wp_create_nonce('wp_rest');\n});\n\nadd_action('rest_api_init', function () {\n $user = get_current_user_id();\n register_rest_route('nonce/v1', 'get', [\n 'methods' =&gt; 'GET',\n 'callback' =&gt; function () use ($user) {\n return [\n 'nonce' =&gt; $GLOBALS['nonce'],\n 'user' =&gt; $user,\n ];\n },\n ]);\n\n register_rest_route('nonce/v1', 'verify', [\n 'methods' =&gt; 'GET',\n 'callback' =&gt; function () use ($user) {\n $nonce = !empty($_GET['nonce']) ? $_GET['nonce'] : false;\n add_filter(\"nonce_user_logged_out\", function ($uid, $action) use ($user) {\n if ($uid === 0 &amp;&amp; $action === 'wp_rest') {\n return $user;\n }\n\n return $uid;\n }, 10, 2);\n\n return [\n 'status' =&gt; wp_verify_nonce($nonce, 'wp_rest'),\n 'user' =&gt; $user,\n ];\n },\n ]);\n});\n</code></pre>\n\n<p>If you spot a security problem with the fix, please give me a shout, right now I can't see anything wrong with it, other than globals.</p>\n" }, { "answer_id": 295543, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Looking at all this code it seems like your problem is the use of closures. At <code>init</code> stage you should only set hooks and not evaluate data as not all of the core had finished loading and being initialized.</p>\n\n<p>In </p>\n\n<pre><code>add_action('rest_api_init', function () {\n $user = get_current_user_id();\n register_rest_route('nonce/v1', 'get', [\n 'methods' =&gt; 'GET',\n 'callback' =&gt; function () use ($user) {\n return [\n 'nonce' =&gt; $GLOBALS['nonce'],\n 'user' =&gt; $user,\n ];\n },\n ]);\n</code></pre>\n\n<p>the <code>$user</code> is bound early to be used in the closure, but no one promises to you that the cookie were already handled and a user was authenticated based on them. A better code will be</p>\n\n<pre><code>add_action('rest_api_init', function () {\n register_rest_route('nonce/v1', 'get', [\n 'methods' =&gt; 'GET',\n 'callback' =&gt; function () {\n $user = get_current_user_id();\n return [\n 'nonce' =&gt; $GLOBALS['nonce'],\n 'user' =&gt; $user,\n ];\n },\n ]);\n</code></pre>\n\n<p>As always with anything hook in wordpress, use the latest hook possible and never try to precalculate anything you don't have to.</p>\n" }, { "answer_id": 295547, "author": "Otto", "author_id": 2232, "author_profile": "https://wordpress.stackexchange.com/users/2232", "pm_score": 3, "selected": true, "text": "<p>Take a closer look at the <code>function rest_cookie_check_errors()</code>.</p>\n\n<p>When you get the nonce via <code>/wp-json/nonce/v1/get</code>, you're not sending a nonce in the first place. So this function nullifies your authentication, with this code:</p>\n\n<pre><code>if ( null === $nonce ) {\n // No nonce at all, so act as if it's an unauthenticated request.\n wp_set_current_user( 0 );\n return true;\n}\n</code></pre>\n\n<p>That's why you're getting a different nonce from your REST call vs getting it from the theme. The REST call is intentionally not recognizing your login credentials (in this case via cookie auth) because you didn't send a valid nonce in the get request.</p>\n\n<p>Now, the reason your wp_loaded code worked was because you got the nonce and saved it to a global before this rest code nullified your login. The verify fails because the rest code nullifies your login before the verify takes place.</p>\n" } ]
2018/02/28
[ "https://wordpress.stackexchange.com/questions/295471", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78685/" ]
**For those that arrive from Google: You [probably shouldn't get the nonces from the REST API](https://github.com/WP-API/docs/pull/20#issuecomment-370286436), unless you *really* know what you're doing. Cookie-based authentication with the REST API is only *meant* for plugins and themes. For a single page application, you should probably use [OAuth](https://wordpress.org/plugins/oauth2-provider/).** This question exists because the documentation isn't/wasn't clear on how should you actually authenticate when building single page apps, JWTs aren't really fit for web apps, and OAuth is harder to implement than cookie based auth. --- [The handbook](https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/) has an example on how the Backbone JavaScript client handles nonces, and if I follow the example, I get a nonce that the built in endpoints such as /wp/v2/posts accepts. ``` \wp_localize_script("client-js", "theme", [ 'nonce' => wp_create_nonce('wp_rest'), 'user' => get_current_user_id(), ]); ``` However, using Backbone is out of the question, and so are themes, so I wrote the following plugin: ``` <?php /* Plugin Name: Nonce Endpoint */ add_action('rest_api_init', function () { $user = get_current_user_id(); register_rest_route('nonce/v1', 'get', [ 'methods' => 'GET', 'callback' => function () use ($user) { return [ 'nonce' => wp_create_nonce('wp_rest'), 'user' => $user, ]; }, ]); register_rest_route('nonce/v1', 'verify', [ 'methods' => 'GET', 'callback' => function () use ($user) { $nonce = !empty($_GET['nonce']) ? $_GET['nonce'] : false; return [ 'valid' => (bool) wp_verify_nonce($nonce, 'wp_rest'), 'user' => $user, ]; }, ]); }); ``` I tinkered in the JavaScript console a bit, and wrote the following: ``` var main = async () => { // var because it can be redefined const nonceReq = await fetch('/wp-json/nonce/v1/get', { credentials: 'include' }) const nonceResp = await nonceReq.json() const nonceValidReq = await fetch(`/wp-json/nonce/v1/verify?nonce=${nonceResp.nonce}`, { credentials: 'include' }) const nonceValidResp = await nonceValidReq.json() const addPost = (nonce) => fetch('/wp-json/wp/v2/posts', { method: 'POST', credentials: 'include', body: JSON.stringify({ title: `Test ${Date.now()}`, content: 'Test', }), headers: { 'X-WP-Nonce': nonce, 'content-type': 'application/json' }, }).then(r => r.json()).then(console.log) console.log(nonceResp.nonce, nonceResp.user, nonceValidResp) console.log(theme.nonce, theme.user) addPost(nonceResp.nonce) addPost(theme.nonce) } main() ``` The expected result is two new posts, but I get `Cookie nonce is invalid` from the first one, and the second one creates the post succesfully. That's probably because the nonces are different, but why? I'm logged in as the same user in both requests. [![enter image description here](https://i.stack.imgur.com/aSif2.png)](https://i.stack.imgur.com/aSif2.png) If my approach is wrong, how should I get the nonce? **Edit**: I tried messing with globals without much luck. Got a bit luckier by utilizing wp\_loaded action: ``` <?php /* Plugin Name: Nonce Endpoint */ $nonce = 'invalid'; add_action('wp_loaded', function () { global $nonce; $nonce = wp_create_nonce('wp_rest'); }); add_action('rest_api_init', function () { $user = get_current_user_id(); register_rest_route('nonce/v1', 'get', [ 'methods' => 'GET', 'callback' => function () use ($user) { return [ 'nonce' => $GLOBALS['nonce'], 'user' => $user, ]; }, ]); register_rest_route('nonce/v1', 'verify', [ 'methods' => 'GET', 'callback' => function () use ($user) { $nonce = !empty($_GET['nonce']) ? $_GET['nonce'] : false; error_log("verify $nonce $user"); return [ 'valid' => (bool) wp_verify_nonce($nonce, 'wp_rest'), 'user' => $user, ]; }, ]); }); ``` Now when I run the JavaScript above, two posts get created, but the verify endpoint fails! [![enter image description here](https://i.stack.imgur.com/P6zzL.png)](https://i.stack.imgur.com/P6zzL.png) I went to debug wp\_verify\_nonce: ``` function wp_verify_nonce( $nonce, $action = -1 ) { $nonce = (string) $nonce; $user = wp_get_current_user(); $uid = (int) $user->ID; // This is 0, even though the verify endpoint says I'm logged in as user 2! ``` I added some logging ``` // Nonce generated 0-12 hours ago $expected = substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), -12, 10 ); error_log("expected 1 $expected received $nonce uid $uid action $action"); if ( hash_equals( $expected, $nonce ) ) { return 1; } // Nonce generated 12-24 hours ago $expected = substr( wp_hash( ( $i - 1 ) . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 ); error_log("expected 2 $expected received $nonce uid $uid action $action"); if ( hash_equals( $expected, $nonce ) ) { return 2; } ``` and the JavaScript code now results in the following entries. As you can see, when the verify endpoint is called, uid is 0. ``` [01-Mar-2018 11:41:57 UTC] verify 716087f772 2 [01-Mar-2018 11:41:57 UTC] expected 1 b35fa18521 received 716087f772 uid 0 action wp_rest [01-Mar-2018 11:41:57 UTC] expected 2 dd35d95cbd received 716087f772 uid 0 action wp_rest [01-Mar-2018 11:41:58 UTC] expected 1 716087f772 received 716087f772 uid 2 action wp_rest [01-Mar-2018 11:41:58 UTC] expected 1 716087f772 received 716087f772 uid 2 action wp_rest ```
Take a closer look at the `function rest_cookie_check_errors()`. When you get the nonce via `/wp-json/nonce/v1/get`, you're not sending a nonce in the first place. So this function nullifies your authentication, with this code: ``` if ( null === $nonce ) { // No nonce at all, so act as if it's an unauthenticated request. wp_set_current_user( 0 ); return true; } ``` That's why you're getting a different nonce from your REST call vs getting it from the theme. The REST call is intentionally not recognizing your login credentials (in this case via cookie auth) because you didn't send a valid nonce in the get request. Now, the reason your wp\_loaded code worked was because you got the nonce and saved it to a global before this rest code nullified your login. The verify fails because the rest code nullifies your login before the verify takes place.
295,489
<p>I've got a wordpress site using MAMP on localhost. Everything's running fine, right up until I try to modify the menu. The menu has about 34 items on it, mostly pages, with a few custom links (placeholders for pages I haven't made yet).</p> <p>When I try to save the menu after modifying it (Adding another page, or a custom link), the menu fails to save correctly. I get a save successful error, but all custom links become first level menu items, the page I was trying to add becomes an empty custom link, and (heres the weird part) the page I was trying to add has its page layout metadata reset. Specifically, the page-top, page-bottom, and the sidebar settings all reset to their default settings. (Which means that suddenly theres a sidebar and a ton of padding, making the page look awful, along with a garbled menu). </p> <p>I found a <a href="https://stackoverflow.com/questions/42019831/wordpress-all-menu-item-pages-turn-into-empty-custom-links-after-17-18-item">few other</a> questions which seemed similiar, and I tried a few fixes, specificlly, adding these lines to mamps php.ini: </p> <pre><code>max_input_vars = 5000 max_execution_time = 600 memory_limit = 64M max_input_time = 600 </code></pre> <p>I can see these values reflected in phpMyAdmin's phpInfo. </p> <p>This seems 100% caused by the server memory limit, but this seems like a really low number to cause it, and the fix provided for the memory limit does not seem to fix this issue. </p> <p>I am able to fix the locations of the items using the menu editor, but once I try to add a new page to the menu, the existing custom links become top level, and the page shows up as a blank custom link. </p> <p>I don't see anything unusual in my debug logs either, just the usual errors: </p> <blockquote> <p>[28-Feb-2018 20:21:03 UTC] PHP Notice: wp_richedit_pre is <strong>deprecated</strong> since version 4.3.0! Use format_for_editor() instead. in /local/wp-includes/functions.php on line 3839 [28-Feb-2018 22:22:52 Europe/Berlin] PHP Fatal error: Call to undefined function luxe_get_meta() in /local/wp-content/themes/simpleflex/index.php on line 3</p> </blockquote> <p>This however, does not fix my problem. I am able to modify the menu using the customizer, but its a poor fix for this issue. (Mostly because there are other staff members who might not remember which way to edit the menu &amp; cause this issue). </p>
[ { "answer_id": 296058, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 0, "selected": false, "text": "<p>I don't have any solution for your problem. At first I thought also on the php value for <code>max_input_vars</code>.</p>\n\n<p>However you should debug about the save process, like the follow small example to get the array with all data from each menu item. This should helps you to unserstand, is the save process ok, is the problem before save on send post data or on the save process.</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: .my Debug\n */\n\nadd_action( 'wp_update_nav_menu', function( $menu_id, $menu_data ) {\n\n var_dump($menu_data);\n\n return $menu_id;\n}, 10, 2 );\n\nadd_action( 'wp_update_nav_menu_item', function( $menu_id, $menu_item_id, $args ) {\n\n echo '&lt;pre&gt;'; var_dump($args); echo '&lt;/pre&gt;';\n\n return $menu_id;\n}, 10, 3 );\n</code></pre>\n\n<p>This two functions debug the menu name at first and after this you should get an output of each menu item, that you would save. You find the functions for this process in <a href=\"https://github.com/WordPress/WordPress/blob/fc6ba86b80a45940407c65773cae0563d64e5c67/wp-admin/includes/nav-menu.php\" rel=\"nofollow noreferrer\"><code>/wp-admin/includes/nav-menu.php</code></a> </p>\n" }, { "answer_id": 296445, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": true, "text": "<p>Obviously, this is non standard WP behaviour, so tons of things could be wrong, but there are some ways to track down the error. The most important thing, I think, is the fact that storing the menu through the customizer works. This means that the function which does the storing of single menu items <a href=\"https://developer.wordpress.org/reference/functions/wp_update_nav_menu_item/\" rel=\"nofollow noreferrer\"><code>wp_update_nav_menu_item</code></a> is functioning correctly, because this function is called directly from the customizer.</p>\n\n<p>The path from the menu page to this function is different, namely through the function <a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu_update_menu_items/\" rel=\"nofollow noreferrer\"><code>wp_nav_menu_update_menu_items</code></a>. Given that things only go wrong once you want to save the menu, something systematically screws up while executing this function, which is not very complex:</p>\n\n<ol>\n<li>Read the current menu as stored in the database</li>\n<li>Loop through all the items in the <code>$_POST</code> variable and call <code>wp_update_nav_menu_item</code> to store them one by one.</li>\n<li>Delete all menu items that were stored in the database but were not in <code>$_POST</code>, so presumably were removed by the user</li>\n</ol>\n\n<p>Under 2 you see a double <code>foreach</code> loop involving multidimensional arrays, which explains why things can get out of hand memorywise (which is why you see the <a href=\"https://wordpress.stackexchange.com/questions/219975/is-there-a-downside-of-using-wp-defer-term-counting\"><code>wp_defer_term_counting</code></a> function at the beginning, to save some memory). My guess would be that memory problems leads to empty values of the <code>$args</code> variable passed to <code>wp_update_nav_menu_item</code> and hence faulty menu items. Since <a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\">menu items are posts</a> in the database a screwup could even lead to the metadata of a page (also a post type) being wiped when the ID of the linked page is passed in stead of the menu item ID, even though there is a test for that at the beginning of <code>wp_update_nav_menu_item</code>.</p>\n\n<p>These days WP needs a 128 MB memory limit, so you should raise that. In my experience 64MB leads to unexpected results regularly.</p>\n\n<p>If that's not possible or doesn't work, there's a workaround. There is a third function you can use to call <code>wp_update_nav_menu_item</code>: <a href=\"https://developer.wordpress.org/reference/functions/wp_save_nav_menu_items/\" rel=\"nofollow noreferrer\"><code>wp_save_nav_menu_items</code></a>. This is an ajax-call that you can build into the menu page to save menu items one by one in stead of having to save the whole menu at once, thus evading memory issues. That would involve adding save buttons to every menu item and removing the general save button. There's a <a href=\"https://rudrastyh.com/wordpress/save-nav-menu-item-individually.html\" rel=\"nofollow noreferrer\">lenghty tutorial here</a>. Not an ideal solution, but if you cannot solve the server issue it could help.</p>\n" } ]
2018/02/28
[ "https://wordpress.stackexchange.com/questions/295489", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92192/" ]
I've got a wordpress site using MAMP on localhost. Everything's running fine, right up until I try to modify the menu. The menu has about 34 items on it, mostly pages, with a few custom links (placeholders for pages I haven't made yet). When I try to save the menu after modifying it (Adding another page, or a custom link), the menu fails to save correctly. I get a save successful error, but all custom links become first level menu items, the page I was trying to add becomes an empty custom link, and (heres the weird part) the page I was trying to add has its page layout metadata reset. Specifically, the page-top, page-bottom, and the sidebar settings all reset to their default settings. (Which means that suddenly theres a sidebar and a ton of padding, making the page look awful, along with a garbled menu). I found a [few other](https://stackoverflow.com/questions/42019831/wordpress-all-menu-item-pages-turn-into-empty-custom-links-after-17-18-item) questions which seemed similiar, and I tried a few fixes, specificlly, adding these lines to mamps php.ini: ``` max_input_vars = 5000 max_execution_time = 600 memory_limit = 64M max_input_time = 600 ``` I can see these values reflected in phpMyAdmin's phpInfo. This seems 100% caused by the server memory limit, but this seems like a really low number to cause it, and the fix provided for the memory limit does not seem to fix this issue. I am able to fix the locations of the items using the menu editor, but once I try to add a new page to the menu, the existing custom links become top level, and the page shows up as a blank custom link. I don't see anything unusual in my debug logs either, just the usual errors: > > [28-Feb-2018 20:21:03 UTC] PHP Notice: wp\_richedit\_pre is **deprecated** since version 4.3.0! Use format\_for\_editor() instead. in /local/wp-includes/functions.php on line 3839 > [28-Feb-2018 22:22:52 Europe/Berlin] PHP Fatal error: Call to undefined function luxe\_get\_meta() in /local/wp-content/themes/simpleflex/index.php on line 3 > > > This however, does not fix my problem. I am able to modify the menu using the customizer, but its a poor fix for this issue. (Mostly because there are other staff members who might not remember which way to edit the menu & cause this issue).
Obviously, this is non standard WP behaviour, so tons of things could be wrong, but there are some ways to track down the error. The most important thing, I think, is the fact that storing the menu through the customizer works. This means that the function which does the storing of single menu items [`wp_update_nav_menu_item`](https://developer.wordpress.org/reference/functions/wp_update_nav_menu_item/) is functioning correctly, because this function is called directly from the customizer. The path from the menu page to this function is different, namely through the function [`wp_nav_menu_update_menu_items`](https://developer.wordpress.org/reference/functions/wp_nav_menu_update_menu_items/). Given that things only go wrong once you want to save the menu, something systematically screws up while executing this function, which is not very complex: 1. Read the current menu as stored in the database 2. Loop through all the items in the `$_POST` variable and call `wp_update_nav_menu_item` to store them one by one. 3. Delete all menu items that were stored in the database but were not in `$_POST`, so presumably were removed by the user Under 2 you see a double `foreach` loop involving multidimensional arrays, which explains why things can get out of hand memorywise (which is why you see the [`wp_defer_term_counting`](https://wordpress.stackexchange.com/questions/219975/is-there-a-downside-of-using-wp-defer-term-counting) function at the beginning, to save some memory). My guess would be that memory problems leads to empty values of the `$args` variable passed to `wp_update_nav_menu_item` and hence faulty menu items. Since [menu items are posts](https://codex.wordpress.org/Post_Types) in the database a screwup could even lead to the metadata of a page (also a post type) being wiped when the ID of the linked page is passed in stead of the menu item ID, even though there is a test for that at the beginning of `wp_update_nav_menu_item`. These days WP needs a 128 MB memory limit, so you should raise that. In my experience 64MB leads to unexpected results regularly. If that's not possible or doesn't work, there's a workaround. There is a third function you can use to call `wp_update_nav_menu_item`: [`wp_save_nav_menu_items`](https://developer.wordpress.org/reference/functions/wp_save_nav_menu_items/). This is an ajax-call that you can build into the menu page to save menu items one by one in stead of having to save the whole menu at once, thus evading memory issues. That would involve adding save buttons to every menu item and removing the general save button. There's a [lenghty tutorial here](https://rudrastyh.com/wordpress/save-nav-menu-item-individually.html). Not an ideal solution, but if you cannot solve the server issue it could help.
295,511
<p>I have a simple endpoint. Its GET, I pass it an ID parameter and it uses this ID to make a curl call. The endpoint then responds with a couple pieces of info json_encoded.</p> <p>The issue is that this endpoint keeps caching its results. How do I keep this from happening?</p> <p>Couple notes:</p> <ol> <li>No caching plugins installed</li> <li>WP config doesn't note caching</li> </ol> <p>The endpoint code is pretty simple:</p> <pre><code>// Get Number of people in line add_action( 'rest_api_init', function () { register_rest_route( 'cc/v1', '/in_line/(?P&lt;id&gt;\d+)', array( 'methods' =&gt; WP_REST_Server::READABLE, 'callback' =&gt; 'in_line', 'args' =&gt; [ 'id' ], ) ); } ); function in_line($data) { //Do a bunch of Curl stuff $response['queue'] = $number; $response['queueID'] = $data['id']; return json_encode($response); } </code></pre> <p>I call the endpoint via jQuery ajax.</p>
[ { "answer_id": 314521, "author": "SungamR", "author_id": 150837, "author_profile": "https://wordpress.stackexchange.com/users/150837", "pm_score": 2, "selected": false, "text": "<p>If you have access to your request header you can add the line.\n<code>Cache-Control: private</code> or <code>Cache-Control: no-cache</code>. This will force well-behaved hosts to send you fresh results.</p>\n" }, { "answer_id": 326167, "author": "Mostafa Soufi", "author_id": 106877, "author_profile": "https://wordpress.stackexchange.com/users/106877", "pm_score": 2, "selected": false, "text": "<p>You should create a new instance from <code>WP_REST_Response</code> to set the Cache-Control value.</p>\n\n<pre><code>&lt;?php\n// Get Number of people in line\nadd_action( 'rest_api_init', function () {\n register_rest_route( 'cc/v1', '/in_line/(?P&lt;id&gt;\\d+)', array(\n 'methods' =&gt; WP_REST_Server::READABLE,\n 'callback' =&gt; 'in_line',\n 'args' =&gt; [\n 'id'\n ],\n ) );\n} );\n\nfunction in_line($data) {\n\n //Do a bunch of Curl stuff\n\n $response['queue'] = $number;\n $response['queueID'] = $data['id'];\n\n $result = new WP_REST_Response($response, 200);\n\n // Set headers.\n $result-&gt;set_headers(array('Cache-Control' =&gt; 'no-cache'));\n\n return $result;\n}\n</code></pre>\n" }, { "answer_id": 397830, "author": "Jewel", "author_id": 16705, "author_profile": "https://wordpress.stackexchange.com/users/16705", "pm_score": 1, "selected": false, "text": "<p>Based on @fränk 's comment the correct and more elegant way will be like this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n// Get Number of people in line\nadd_action( 'rest_api_init', function () {\n register_rest_route( 'cc/v1', '/in_line/(?P&lt;id&gt;\\d+)', array(\n 'methods' =&gt; WP_REST_Server::READABLE,\n 'callback' =&gt; 'in_line',\n 'args' =&gt; [\n 'id'\n ],\n ) );\n} );\n\nfunction in_line($data) {\n\n //Do a bunch of Curl stuff\n\n $response['queue'] = $number;\n $response['queueID'] = $data['id'];\n\n nocache_headers();\n\n $result = new WP_REST_Response($response, 200);\n\n return $result;\n}\n</code></pre>\n" } ]
2018/03/01
[ "https://wordpress.stackexchange.com/questions/295511", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/5181/" ]
I have a simple endpoint. Its GET, I pass it an ID parameter and it uses this ID to make a curl call. The endpoint then responds with a couple pieces of info json\_encoded. The issue is that this endpoint keeps caching its results. How do I keep this from happening? Couple notes: 1. No caching plugins installed 2. WP config doesn't note caching The endpoint code is pretty simple: ``` // Get Number of people in line add_action( 'rest_api_init', function () { register_rest_route( 'cc/v1', '/in_line/(?P<id>\d+)', array( 'methods' => WP_REST_Server::READABLE, 'callback' => 'in_line', 'args' => [ 'id' ], ) ); } ); function in_line($data) { //Do a bunch of Curl stuff $response['queue'] = $number; $response['queueID'] = $data['id']; return json_encode($response); } ``` I call the endpoint via jQuery ajax.
If you have access to your request header you can add the line. `Cache-Control: private` or `Cache-Control: no-cache`. This will force well-behaved hosts to send you fresh results.
295,558
<p>I intend to programmatically create a widget area for each product category within WooCommerce.</p> <p>I currently have the following code in my <code>functions.php</code>:</p> <pre><code>function add_widget_areas() { $args = array( 'taxonomy' =&gt; 'product_cat', 'hide_empty' =&gt; false, 'parent' =&gt; 0, ); $product_cats = get_terms( $args ); foreach ( $product_cats as $product_cat ) { register_sidebar( array( 'name' =&gt; 'Filter sidebar -' . $product_cat-&gt;name, 'id' =&gt; 'filter_sidebar_' . $product_cat-&gt;name, 'before_widget' =&gt; '&lt;div class="filter-sidebar-' . $product_cat-&gt;name . '"&gt;', 'after_widget' =&gt; '&lt;/div&gt;', 'before_title' =&gt; '&lt;h2 class="filter-title"&gt;', 'after_title' =&gt; '&lt;/h2&gt;', ) ); } } add_action( 'widgets_init', 'add_widget_areas' ); </code></pre> <p>My problem is that this returns an error: <code>Notice: Trying to get property of non-object in .../functions.php on line 752</code> (line 752: <code>'name' =&gt; 'Filter sidebar -' . $product_cat-&gt;name,</code>), presumably because the action for registering widget areas fires before WooCommerce has initialised its product categories.</p> <p>How do I access the product categories this early in order to make this loop work?</p>
[ { "answer_id": 295545, "author": "Atif Aqeel", "author_id": 136891, "author_profile": "https://wordpress.stackexchange.com/users/136891", "pm_score": 1, "selected": false, "text": "<p>this is shortcode this coming from the sidebar, go to appearance -> widget. select the sidebar and remove shortcode. </p>\n" }, { "answer_id": 295546, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": true, "text": "<p>This is a shortcode of the <a href=\"https://wordpress.org/plugins/popup-builder/\" rel=\"nofollow noreferrer\">Popup builder plugin</a> that for some reason is not being evaluated. Is that plugin installed?</p>\n\n<p>Most likely the shortcode is in a widget somewhere. It could also be in a theme file.</p>\n" } ]
2018/03/01
[ "https://wordpress.stackexchange.com/questions/295558", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137798/" ]
I intend to programmatically create a widget area for each product category within WooCommerce. I currently have the following code in my `functions.php`: ``` function add_widget_areas() { $args = array( 'taxonomy' => 'product_cat', 'hide_empty' => false, 'parent' => 0, ); $product_cats = get_terms( $args ); foreach ( $product_cats as $product_cat ) { register_sidebar( array( 'name' => 'Filter sidebar -' . $product_cat->name, 'id' => 'filter_sidebar_' . $product_cat->name, 'before_widget' => '<div class="filter-sidebar-' . $product_cat->name . '">', 'after_widget' => '</div>', 'before_title' => '<h2 class="filter-title">', 'after_title' => '</h2>', ) ); } } add_action( 'widgets_init', 'add_widget_areas' ); ``` My problem is that this returns an error: `Notice: Trying to get property of non-object in .../functions.php on line 752` (line 752: `'name' => 'Filter sidebar -' . $product_cat->name,`), presumably because the action for registering widget areas fires before WooCommerce has initialised its product categories. How do I access the product categories this early in order to make this loop work?
This is a shortcode of the [Popup builder plugin](https://wordpress.org/plugins/popup-builder/) that for some reason is not being evaluated. Is that plugin installed? Most likely the shortcode is in a widget somewhere. It could also be in a theme file.
295,570
<p>i have script which displays iframe after certain seconds.</p> <pre><code>&lt;script type="text/javascript"&gt;//&lt;![CDATA[ $(window).load(function(){ setTimeout(function(){ $(".hidden_div").show(function(){ $(this).find("iframe").prop("src", function(){ return $(this).data("src"); }); }); }, 5000); });//]]&gt; &lt;/script&gt; </code></pre> <p>But it works with only code.jquery.com/jquery-1.8.3.js i am using wordpress's jquery 1.12.4</p> <p>If i use both then i get lot of jquery errors from theme.</p> <p>how to make the script work with 1.12.4 jquery?</p>
[ { "answer_id": 295573, "author": "Xhynk", "author_id": 13724, "author_profile": "https://wordpress.stackexchange.com/users/13724", "pm_score": 2, "selected": true, "text": "<p>If you only have one iframe, just set the iframe's <code>src</code> attribute in the <code>.show()</code> callback function.</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;//&lt;![CDATA[\n jQuery(window).load(function($){\n setTimeout(function(){\n $('.hidden_div').show(function(){\n $(this).find('iframe').attr('src', 'https://example.com/');\n });\n }, 5000);\n });//]]&gt; \n&lt;/script&gt;\n</code></pre>\n\n<p>If you need more dynamic code, remove the <code>src</code> attribute of the iframe, and add a new attribute with the url like so</p>\n\n<pre><code>&lt;iframe data-src=\"https://example.com/\"&gt;&lt;/iframe&gt;\n</code></pre>\n\n<p>And then clone the data attribute to the src attribute like so:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;//&lt;![CDATA[\n jQuery(window).load(function($){\n setTimeout(function(){\n $('.hidden_div').show(function(){\n var src = $(this).find('iframe').attr('data-src');\n $(this).find('iframe').attr('src', src);\n });\n }, 5000);\n });//]]&gt; \n&lt;/script&gt;\n</code></pre>\n\n<p>If you want to use the original code you have, this will work. The problem is you don't have the <code>$</code> jQuery alias defined yet.</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;//&lt;![CDATA[\n jQuery(window).load(function($){\n setTimeout(function(){\n $(\".hidden_div\").show(function(){\n $(this).find(\"iframe\").prop(\"src\", function(){\n return $(this).data(\"src\");\n });\n });\n }, 5000);\n });//]]&gt; \n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 295578, "author": "Akshat", "author_id": 114978, "author_profile": "https://wordpress.stackexchange.com/users/114978", "pm_score": -1, "selected": false, "text": "<p>It's jQuery issue, not WordPress related, try with</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;//&lt;![CDATA[\njQuery(window).load(function(){\n setTimeout(function(){\n jQuery(\".hidden_div\").show(function(){\n jQuery(this).find(\"iframe\").prop(\"src\", function(){\n return jQuery(this).data(\"src\");\n });\n });\n }, 5000);\n});//]]&gt; \n&lt;/script&gt;\n</code></pre>\n" } ]
2018/03/01
[ "https://wordpress.stackexchange.com/questions/295570", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86147/" ]
i have script which displays iframe after certain seconds. ``` <script type="text/javascript">//<![CDATA[ $(window).load(function(){ setTimeout(function(){ $(".hidden_div").show(function(){ $(this).find("iframe").prop("src", function(){ return $(this).data("src"); }); }); }, 5000); });//]]> </script> ``` But it works with only code.jquery.com/jquery-1.8.3.js i am using wordpress's jquery 1.12.4 If i use both then i get lot of jquery errors from theme. how to make the script work with 1.12.4 jquery?
If you only have one iframe, just set the iframe's `src` attribute in the `.show()` callback function. ``` <script type="text/javascript">//<![CDATA[ jQuery(window).load(function($){ setTimeout(function(){ $('.hidden_div').show(function(){ $(this).find('iframe').attr('src', 'https://example.com/'); }); }, 5000); });//]]> </script> ``` If you need more dynamic code, remove the `src` attribute of the iframe, and add a new attribute with the url like so ``` <iframe data-src="https://example.com/"></iframe> ``` And then clone the data attribute to the src attribute like so: ``` <script type="text/javascript">//<![CDATA[ jQuery(window).load(function($){ setTimeout(function(){ $('.hidden_div').show(function(){ var src = $(this).find('iframe').attr('data-src'); $(this).find('iframe').attr('src', src); }); }, 5000); });//]]> </script> ``` If you want to use the original code you have, this will work. The problem is you don't have the `$` jQuery alias defined yet. ``` <script type="text/javascript">//<![CDATA[ jQuery(window).load(function($){ setTimeout(function(){ $(".hidden_div").show(function(){ $(this).find("iframe").prop("src", function(){ return $(this).data("src"); }); }); }, 5000); });//]]> </script> ```
295,596
<p>i want to auto add custom field value when post publish , my custom fields name is "quality" and the value is "HD" .</p> <p>i've look through this site and apparently codes i found is not working. so far i've tried this code :</p> <pre><code>/* Do something with the data entered */ add_action( 'save_post', 'myplugin_save_postdata' ); function myplugin_save_postdata( $post_id ) { if ( 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) return; } else { if ( ! current_user_can( 'edit_post', $post_id ) ) return; } $mydata = 'quality'; // Do something with $mydata update_post_meta( $post_id, 'HD', $mydata ); } </code></pre> <p>and also this code</p> <pre><code>add_action('publish_page', 'add_custom_field_automatically'); add_action('publish_post', 'add_custom_field_automatically'); function add_custom_field_automatically($post_ID) { global $wpdb; if(!wp_is_post_revision($post_ID)) { add_post_meta($post_ID, 'quality', 'HD', true); } } </code></pre> <p>follow instructions and put that code above on my functions.php , and nothing happend. custom fields still empty , and i look the post on homepage and no value added.</p> <p>thank you! i hope my question is clear enough to understand.</p>
[ { "answer_id": 295573, "author": "Xhynk", "author_id": 13724, "author_profile": "https://wordpress.stackexchange.com/users/13724", "pm_score": 2, "selected": true, "text": "<p>If you only have one iframe, just set the iframe's <code>src</code> attribute in the <code>.show()</code> callback function.</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;//&lt;![CDATA[\n jQuery(window).load(function($){\n setTimeout(function(){\n $('.hidden_div').show(function(){\n $(this).find('iframe').attr('src', 'https://example.com/');\n });\n }, 5000);\n });//]]&gt; \n&lt;/script&gt;\n</code></pre>\n\n<p>If you need more dynamic code, remove the <code>src</code> attribute of the iframe, and add a new attribute with the url like so</p>\n\n<pre><code>&lt;iframe data-src=\"https://example.com/\"&gt;&lt;/iframe&gt;\n</code></pre>\n\n<p>And then clone the data attribute to the src attribute like so:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;//&lt;![CDATA[\n jQuery(window).load(function($){\n setTimeout(function(){\n $('.hidden_div').show(function(){\n var src = $(this).find('iframe').attr('data-src');\n $(this).find('iframe').attr('src', src);\n });\n }, 5000);\n });//]]&gt; \n&lt;/script&gt;\n</code></pre>\n\n<p>If you want to use the original code you have, this will work. The problem is you don't have the <code>$</code> jQuery alias defined yet.</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;//&lt;![CDATA[\n jQuery(window).load(function($){\n setTimeout(function(){\n $(\".hidden_div\").show(function(){\n $(this).find(\"iframe\").prop(\"src\", function(){\n return $(this).data(\"src\");\n });\n });\n }, 5000);\n });//]]&gt; \n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 295578, "author": "Akshat", "author_id": 114978, "author_profile": "https://wordpress.stackexchange.com/users/114978", "pm_score": -1, "selected": false, "text": "<p>It's jQuery issue, not WordPress related, try with</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;//&lt;![CDATA[\njQuery(window).load(function(){\n setTimeout(function(){\n jQuery(\".hidden_div\").show(function(){\n jQuery(this).find(\"iframe\").prop(\"src\", function(){\n return jQuery(this).data(\"src\");\n });\n });\n }, 5000);\n});//]]&gt; \n&lt;/script&gt;\n</code></pre>\n" } ]
2018/03/02
[ "https://wordpress.stackexchange.com/questions/295596", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136816/" ]
i want to auto add custom field value when post publish , my custom fields name is "quality" and the value is "HD" . i've look through this site and apparently codes i found is not working. so far i've tried this code : ``` /* Do something with the data entered */ add_action( 'save_post', 'myplugin_save_postdata' ); function myplugin_save_postdata( $post_id ) { if ( 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) return; } else { if ( ! current_user_can( 'edit_post', $post_id ) ) return; } $mydata = 'quality'; // Do something with $mydata update_post_meta( $post_id, 'HD', $mydata ); } ``` and also this code ``` add_action('publish_page', 'add_custom_field_automatically'); add_action('publish_post', 'add_custom_field_automatically'); function add_custom_field_automatically($post_ID) { global $wpdb; if(!wp_is_post_revision($post_ID)) { add_post_meta($post_ID, 'quality', 'HD', true); } } ``` follow instructions and put that code above on my functions.php , and nothing happend. custom fields still empty , and i look the post on homepage and no value added. thank you! i hope my question is clear enough to understand.
If you only have one iframe, just set the iframe's `src` attribute in the `.show()` callback function. ``` <script type="text/javascript">//<![CDATA[ jQuery(window).load(function($){ setTimeout(function(){ $('.hidden_div').show(function(){ $(this).find('iframe').attr('src', 'https://example.com/'); }); }, 5000); });//]]> </script> ``` If you need more dynamic code, remove the `src` attribute of the iframe, and add a new attribute with the url like so ``` <iframe data-src="https://example.com/"></iframe> ``` And then clone the data attribute to the src attribute like so: ``` <script type="text/javascript">//<![CDATA[ jQuery(window).load(function($){ setTimeout(function(){ $('.hidden_div').show(function(){ var src = $(this).find('iframe').attr('data-src'); $(this).find('iframe').attr('src', src); }); }, 5000); });//]]> </script> ``` If you want to use the original code you have, this will work. The problem is you don't have the `$` jQuery alias defined yet. ``` <script type="text/javascript">//<![CDATA[ jQuery(window).load(function($){ setTimeout(function(){ $(".hidden_div").show(function(){ $(this).find("iframe").prop("src", function(){ return $(this).data("src"); }); }); }, 5000); });//]]> </script> ```
295,617
<p>I understand <em>how</em> to use <code>get_post_metadata()</code>, however this code in a custom RSS feed template:</p> <pre><code>while( have_posts()) : the_post(); // Has a custom URL been supplied? Use that in preference. $feature_permalink = ‌‌get_post_meta(get_the_ID(), '_featureurl', true); [...] </code></pre> <p>is giving:</p> <blockquote> <p>HP Fatal error: Uncaught Error: Call to undefined function ‌‌get_post_meta() in /srv/www/foo/htdocs/wp-content/themes/bar/feed-feature.php</p> </blockquote> <p>(and indeed the PhpStorm editor highlights it accordingly, but with an xdebug breakpoint set, I can run it fine in the debug console. All the other various feed function calls - for the standard permalink, title, guid etc. - work fine.)</p> <p>The template is in <code>functions.php</code>, called with:</p> <pre><code>function foo_custom_rss() { if ( in_array('feature', get_query_var('post_type')) ) { get_template_part( 'feed', 'feature' ); } else { get_template_part( 'feed', 'rss2' ); } } remove_all_actions( 'do_feed_rss2' ); add_action( 'do_feed_rss2', 'foo_custom_rss', 10, 1 ); </code></pre>
[ { "answer_id": 295750, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 1, "selected": false, "text": "<p>To modify an RSS item's <code>&lt;link&gt;</code> node value, use the <code>the_permalink_rss</code> filter. This is demonstrated in the code below where if a <code>feature</code> post has a value set for <code>_featureurl</code>, we will return the custom value. Otherwise, the default permalink is returned:</p>\n\n<pre><code>/**\n * Filters the permalink to the post for use in feeds.\n *\n * @param string $post_permalink The current post permalink.\n */\nadd_filter( 'the_permalink_rss', 'wpse_the_permalink_rss', 10, 1 );\nfunction wpse_the_permalink_rss( $post_permalink ) {\n // Bail if this is not a feature.\n if ( 'feature' !== get_query_var( 'post_type') ) {\n return $post_permalink;\n }\n\n // Get the permalink URL.\n $feature_permalink = get_post_meta( \n get_the_ID(),\n '_featureurl',\n true \n );\n\n // If the the custom URL has been specified return it, otherwise, use default permalink.\n // Note: This is run through esc_url() via the_permalink_rss().\n if ( $feature_permalink ) {\n return $feature_permalink; \n } else {\n return $post_permalink; \n }\n}\n</code></pre>\n\n<p>Example RSS output for the <code>feature</code> post type, which has the following URL:</p>\n\n<p><code>http://example.com/feed/?post_type=feature</code></p>\n\n<p>Note that the <code>&lt;link&gt;</code> node under the <code>&lt;item&gt;</code> node contains the URL <code>https://google.com</code>, which is what I set for the <code>_featureurl</code> custom field:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;rss version=\"2.0\"\n xmlns:content=\"http://purl.org/rss/1.0/modules/content/\"\n xmlns:wfw=\"http://wellformedweb.org/CommentAPI/\"\n xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n xmlns:atom=\"http://www.w3.org/2005/Atom\"\n xmlns:sy=\"http://purl.org/rss/1.0/modules/syndication/\"\n xmlns:slash=\"http://purl.org/rss/1.0/modules/slash/\"\n &gt;\n\n&lt;channel&gt;\n &lt;title&gt;Features &amp;#8211; WP Theme Testing&lt;/title&gt;\n &lt;atom:link href=\"http://localhost/wp-theme-testing/feed/?post_type=feature\" rel=\"self\" type=\"application/rss+xml\" /&gt;\n &lt;link&gt;http://localhost/wp-theme-testing&lt;/link&gt;\n &lt;description&gt;I &amp;#60;3 testing themes!&lt;/description&gt;\n &lt;lastBuildDate&gt;Sun, 04 Mar 2018 05:46:16 +0000&lt;/lastBuildDate&gt;\n &lt;language&gt;en-US&lt;/language&gt;\n &lt;sy:updatePeriod&gt;hourly&lt;/sy:updatePeriod&gt;\n &lt;sy:updateFrequency&gt;1&lt;/sy:updateFrequency&gt;\n &lt;generator&gt;https://wordpress.org/?v=4.9.1&lt;/generator&gt;\n\n&lt;image&gt;\n &lt;url&gt;http://localhost/wp-theme-testing/wp-content/uploads/2017/06/cropped-favicon-32x32.png&lt;/url&gt;\n &lt;title&gt;Features &amp;#8211; WP Theme Testing&lt;/title&gt;\n &lt;link&gt;http://localhost/wp-theme-testing&lt;/link&gt;\n &lt;width&gt;32&lt;/width&gt;\n &lt;height&gt;32&lt;/height&gt;\n&lt;/image&gt; \n &lt;item&gt;\n &lt;title&gt;test feature&lt;/title&gt;\n &lt;link&gt;https://google.com&lt;/link&gt;\n\n\n &lt;comments&gt;http://localhost/wp-theme-testing/feartures/test-feature/#respond&lt;/comments&gt;\n &lt;pubDate&gt;Sun, 04 Mar 2018 05:41:29 +0000&lt;/pubDate&gt;\n &lt;dc:creator&gt;&lt;![CDATA[dave]]&gt;&lt;/dc:creator&gt;\n\n &lt;guid isPermaLink=\"false\"&gt;http://localhost/wp-theme-testing/?post_type=feature&amp;#038;p=3035&lt;/guid&gt;\n &lt;description&gt;&lt;![CDATA[a test!]]&gt;&lt;/description&gt;\n &lt;content:encoded&gt;&lt;![CDATA[&lt;p&gt;a test!&lt;/p&gt;\n]]&gt;&lt;/content:encoded&gt;\n &lt;wfw:commentRss&gt;http://localhost/wp-theme-testing/feartures/test-feature/feed/&lt;/wfw:commentRss&gt;\n &lt;slash:comments&gt;0&lt;/slash:comments&gt;\n &lt;/item&gt;\n &lt;/channel&gt;\n&lt;/rss&gt;\n</code></pre>\n" }, { "answer_id": 298119, "author": "William Turrell", "author_id": 42868, "author_profile": "https://wordpress.stackexchange.com/users/42868", "pm_score": 1, "selected": true, "text": "<p>This is a workaround, but it did solve things for me.</p>\n\n<p>First I moved this site from my vvv to vvv2 dev environment, to rule out anything odd there. Then I went through the WP config files and the rest of functions.php carefully looking for anything with the potential to break things. </p>\n\n<p>No luck so far.</p>\n\n<p>I traced <em>get_post_meta()</em> in the source, thinking I might only be able to solve this by rewriting an equivalent function myself (creating a DB query if necessary) - as readers may know it's simply a wrapper for <a href=\"https://developer.wordpress.org/reference/functions/get_metadata/\" rel=\"nofollow noreferrer\">get_metadata()</a> - for some reason this <em>does</em> work. </p>\n\n<p>So if anyone can suggest why get_post_meta() is undefined and get_metadata() isn't...</p>\n" } ]
2018/03/02
[ "https://wordpress.stackexchange.com/questions/295617", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/42868/" ]
I understand *how* to use `get_post_metadata()`, however this code in a custom RSS feed template: ``` while( have_posts()) : the_post(); // Has a custom URL been supplied? Use that in preference. $feature_permalink = ‌‌get_post_meta(get_the_ID(), '_featureurl', true); [...] ``` is giving: > > HP Fatal error: Uncaught Error: Call to undefined function > ‌‌get\_post\_meta() in > /srv/www/foo/htdocs/wp-content/themes/bar/feed-feature.php > > > (and indeed the PhpStorm editor highlights it accordingly, but with an xdebug breakpoint set, I can run it fine in the debug console. All the other various feed function calls - for the standard permalink, title, guid etc. - work fine.) The template is in `functions.php`, called with: ``` function foo_custom_rss() { if ( in_array('feature', get_query_var('post_type')) ) { get_template_part( 'feed', 'feature' ); } else { get_template_part( 'feed', 'rss2' ); } } remove_all_actions( 'do_feed_rss2' ); add_action( 'do_feed_rss2', 'foo_custom_rss', 10, 1 ); ```
This is a workaround, but it did solve things for me. First I moved this site from my vvv to vvv2 dev environment, to rule out anything odd there. Then I went through the WP config files and the rest of functions.php carefully looking for anything with the potential to break things. No luck so far. I traced *get\_post\_meta()* in the source, thinking I might only be able to solve this by rewriting an equivalent function myself (creating a DB query if necessary) - as readers may know it's simply a wrapper for [get\_metadata()](https://developer.wordpress.org/reference/functions/get_metadata/) - for some reason this *does* work. So if anyone can suggest why get\_post\_meta() is undefined and get\_metadata() isn't...
295,630
<p>I've a custom Post Type i.e. <code>prj</code> and need to auto increment it's <code>post_title</code> (title) and <code>post_name</code> (slug) on post save, update regardless of the post status .. the post can never be deleted that's why it won't be an issue ..</p> <p>Need it to behave just like AutoIncrement field in SQL .. once an ID is assigned, it should never be replicated ..</p> <p>So far, I've reached to the code mentioned below .. but the problem is it is only setting up the post title, not the slug and the increment feature is not working as well ..</p> <pre><code>add_filter( 'wp_insert_post_data' , 'odin_prj_title' , '99', 2 ); function odin_prj_title( $data , $postarr ) { if( $data['post_type'] == 'prj' ) { $last_post = wp_get_recent_posts( '1'); $last_post_ID = (int)$last_post['0']['ID']; $data['post_title'] = 'P0' . ($last_post_ID + 1); } return $data; } </code></pre>
[ { "answer_id": 295750, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 1, "selected": false, "text": "<p>To modify an RSS item's <code>&lt;link&gt;</code> node value, use the <code>the_permalink_rss</code> filter. This is demonstrated in the code below where if a <code>feature</code> post has a value set for <code>_featureurl</code>, we will return the custom value. Otherwise, the default permalink is returned:</p>\n\n<pre><code>/**\n * Filters the permalink to the post for use in feeds.\n *\n * @param string $post_permalink The current post permalink.\n */\nadd_filter( 'the_permalink_rss', 'wpse_the_permalink_rss', 10, 1 );\nfunction wpse_the_permalink_rss( $post_permalink ) {\n // Bail if this is not a feature.\n if ( 'feature' !== get_query_var( 'post_type') ) {\n return $post_permalink;\n }\n\n // Get the permalink URL.\n $feature_permalink = get_post_meta( \n get_the_ID(),\n '_featureurl',\n true \n );\n\n // If the the custom URL has been specified return it, otherwise, use default permalink.\n // Note: This is run through esc_url() via the_permalink_rss().\n if ( $feature_permalink ) {\n return $feature_permalink; \n } else {\n return $post_permalink; \n }\n}\n</code></pre>\n\n<p>Example RSS output for the <code>feature</code> post type, which has the following URL:</p>\n\n<p><code>http://example.com/feed/?post_type=feature</code></p>\n\n<p>Note that the <code>&lt;link&gt;</code> node under the <code>&lt;item&gt;</code> node contains the URL <code>https://google.com</code>, which is what I set for the <code>_featureurl</code> custom field:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;rss version=\"2.0\"\n xmlns:content=\"http://purl.org/rss/1.0/modules/content/\"\n xmlns:wfw=\"http://wellformedweb.org/CommentAPI/\"\n xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n xmlns:atom=\"http://www.w3.org/2005/Atom\"\n xmlns:sy=\"http://purl.org/rss/1.0/modules/syndication/\"\n xmlns:slash=\"http://purl.org/rss/1.0/modules/slash/\"\n &gt;\n\n&lt;channel&gt;\n &lt;title&gt;Features &amp;#8211; WP Theme Testing&lt;/title&gt;\n &lt;atom:link href=\"http://localhost/wp-theme-testing/feed/?post_type=feature\" rel=\"self\" type=\"application/rss+xml\" /&gt;\n &lt;link&gt;http://localhost/wp-theme-testing&lt;/link&gt;\n &lt;description&gt;I &amp;#60;3 testing themes!&lt;/description&gt;\n &lt;lastBuildDate&gt;Sun, 04 Mar 2018 05:46:16 +0000&lt;/lastBuildDate&gt;\n &lt;language&gt;en-US&lt;/language&gt;\n &lt;sy:updatePeriod&gt;hourly&lt;/sy:updatePeriod&gt;\n &lt;sy:updateFrequency&gt;1&lt;/sy:updateFrequency&gt;\n &lt;generator&gt;https://wordpress.org/?v=4.9.1&lt;/generator&gt;\n\n&lt;image&gt;\n &lt;url&gt;http://localhost/wp-theme-testing/wp-content/uploads/2017/06/cropped-favicon-32x32.png&lt;/url&gt;\n &lt;title&gt;Features &amp;#8211; WP Theme Testing&lt;/title&gt;\n &lt;link&gt;http://localhost/wp-theme-testing&lt;/link&gt;\n &lt;width&gt;32&lt;/width&gt;\n &lt;height&gt;32&lt;/height&gt;\n&lt;/image&gt; \n &lt;item&gt;\n &lt;title&gt;test feature&lt;/title&gt;\n &lt;link&gt;https://google.com&lt;/link&gt;\n\n\n &lt;comments&gt;http://localhost/wp-theme-testing/feartures/test-feature/#respond&lt;/comments&gt;\n &lt;pubDate&gt;Sun, 04 Mar 2018 05:41:29 +0000&lt;/pubDate&gt;\n &lt;dc:creator&gt;&lt;![CDATA[dave]]&gt;&lt;/dc:creator&gt;\n\n &lt;guid isPermaLink=\"false\"&gt;http://localhost/wp-theme-testing/?post_type=feature&amp;#038;p=3035&lt;/guid&gt;\n &lt;description&gt;&lt;![CDATA[a test!]]&gt;&lt;/description&gt;\n &lt;content:encoded&gt;&lt;![CDATA[&lt;p&gt;a test!&lt;/p&gt;\n]]&gt;&lt;/content:encoded&gt;\n &lt;wfw:commentRss&gt;http://localhost/wp-theme-testing/feartures/test-feature/feed/&lt;/wfw:commentRss&gt;\n &lt;slash:comments&gt;0&lt;/slash:comments&gt;\n &lt;/item&gt;\n &lt;/channel&gt;\n&lt;/rss&gt;\n</code></pre>\n" }, { "answer_id": 298119, "author": "William Turrell", "author_id": 42868, "author_profile": "https://wordpress.stackexchange.com/users/42868", "pm_score": 1, "selected": true, "text": "<p>This is a workaround, but it did solve things for me.</p>\n\n<p>First I moved this site from my vvv to vvv2 dev environment, to rule out anything odd there. Then I went through the WP config files and the rest of functions.php carefully looking for anything with the potential to break things. </p>\n\n<p>No luck so far.</p>\n\n<p>I traced <em>get_post_meta()</em> in the source, thinking I might only be able to solve this by rewriting an equivalent function myself (creating a DB query if necessary) - as readers may know it's simply a wrapper for <a href=\"https://developer.wordpress.org/reference/functions/get_metadata/\" rel=\"nofollow noreferrer\">get_metadata()</a> - for some reason this <em>does</em> work. </p>\n\n<p>So if anyone can suggest why get_post_meta() is undefined and get_metadata() isn't...</p>\n" } ]
2018/03/02
[ "https://wordpress.stackexchange.com/questions/295630", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58627/" ]
I've a custom Post Type i.e. `prj` and need to auto increment it's `post_title` (title) and `post_name` (slug) on post save, update regardless of the post status .. the post can never be deleted that's why it won't be an issue .. Need it to behave just like AutoIncrement field in SQL .. once an ID is assigned, it should never be replicated .. So far, I've reached to the code mentioned below .. but the problem is it is only setting up the post title, not the slug and the increment feature is not working as well .. ``` add_filter( 'wp_insert_post_data' , 'odin_prj_title' , '99', 2 ); function odin_prj_title( $data , $postarr ) { if( $data['post_type'] == 'prj' ) { $last_post = wp_get_recent_posts( '1'); $last_post_ID = (int)$last_post['0']['ID']; $data['post_title'] = 'P0' . ($last_post_ID + 1); } return $data; } ```
This is a workaround, but it did solve things for me. First I moved this site from my vvv to vvv2 dev environment, to rule out anything odd there. Then I went through the WP config files and the rest of functions.php carefully looking for anything with the potential to break things. No luck so far. I traced *get\_post\_meta()* in the source, thinking I might only be able to solve this by rewriting an equivalent function myself (creating a DB query if necessary) - as readers may know it's simply a wrapper for [get\_metadata()](https://developer.wordpress.org/reference/functions/get_metadata/) - for some reason this *does* work. So if anyone can suggest why get\_post\_meta() is undefined and get\_metadata() isn't...
295,641
<pre><code>&lt;title&gt; &lt;?php if ( is_single() ) { single_post_title('', true); } else { bloginfo('name'); echo " - "; bloginfo('description'); } ?&gt; &lt;/title&gt; </code></pre> <p>This is my title tag code used for my wordpress blog. But Seo analyst shows <code>No title tag</code> found error</p>
[ { "answer_id": 295750, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 1, "selected": false, "text": "<p>To modify an RSS item's <code>&lt;link&gt;</code> node value, use the <code>the_permalink_rss</code> filter. This is demonstrated in the code below where if a <code>feature</code> post has a value set for <code>_featureurl</code>, we will return the custom value. Otherwise, the default permalink is returned:</p>\n\n<pre><code>/**\n * Filters the permalink to the post for use in feeds.\n *\n * @param string $post_permalink The current post permalink.\n */\nadd_filter( 'the_permalink_rss', 'wpse_the_permalink_rss', 10, 1 );\nfunction wpse_the_permalink_rss( $post_permalink ) {\n // Bail if this is not a feature.\n if ( 'feature' !== get_query_var( 'post_type') ) {\n return $post_permalink;\n }\n\n // Get the permalink URL.\n $feature_permalink = get_post_meta( \n get_the_ID(),\n '_featureurl',\n true \n );\n\n // If the the custom URL has been specified return it, otherwise, use default permalink.\n // Note: This is run through esc_url() via the_permalink_rss().\n if ( $feature_permalink ) {\n return $feature_permalink; \n } else {\n return $post_permalink; \n }\n}\n</code></pre>\n\n<p>Example RSS output for the <code>feature</code> post type, which has the following URL:</p>\n\n<p><code>http://example.com/feed/?post_type=feature</code></p>\n\n<p>Note that the <code>&lt;link&gt;</code> node under the <code>&lt;item&gt;</code> node contains the URL <code>https://google.com</code>, which is what I set for the <code>_featureurl</code> custom field:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;rss version=\"2.0\"\n xmlns:content=\"http://purl.org/rss/1.0/modules/content/\"\n xmlns:wfw=\"http://wellformedweb.org/CommentAPI/\"\n xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n xmlns:atom=\"http://www.w3.org/2005/Atom\"\n xmlns:sy=\"http://purl.org/rss/1.0/modules/syndication/\"\n xmlns:slash=\"http://purl.org/rss/1.0/modules/slash/\"\n &gt;\n\n&lt;channel&gt;\n &lt;title&gt;Features &amp;#8211; WP Theme Testing&lt;/title&gt;\n &lt;atom:link href=\"http://localhost/wp-theme-testing/feed/?post_type=feature\" rel=\"self\" type=\"application/rss+xml\" /&gt;\n &lt;link&gt;http://localhost/wp-theme-testing&lt;/link&gt;\n &lt;description&gt;I &amp;#60;3 testing themes!&lt;/description&gt;\n &lt;lastBuildDate&gt;Sun, 04 Mar 2018 05:46:16 +0000&lt;/lastBuildDate&gt;\n &lt;language&gt;en-US&lt;/language&gt;\n &lt;sy:updatePeriod&gt;hourly&lt;/sy:updatePeriod&gt;\n &lt;sy:updateFrequency&gt;1&lt;/sy:updateFrequency&gt;\n &lt;generator&gt;https://wordpress.org/?v=4.9.1&lt;/generator&gt;\n\n&lt;image&gt;\n &lt;url&gt;http://localhost/wp-theme-testing/wp-content/uploads/2017/06/cropped-favicon-32x32.png&lt;/url&gt;\n &lt;title&gt;Features &amp;#8211; WP Theme Testing&lt;/title&gt;\n &lt;link&gt;http://localhost/wp-theme-testing&lt;/link&gt;\n &lt;width&gt;32&lt;/width&gt;\n &lt;height&gt;32&lt;/height&gt;\n&lt;/image&gt; \n &lt;item&gt;\n &lt;title&gt;test feature&lt;/title&gt;\n &lt;link&gt;https://google.com&lt;/link&gt;\n\n\n &lt;comments&gt;http://localhost/wp-theme-testing/feartures/test-feature/#respond&lt;/comments&gt;\n &lt;pubDate&gt;Sun, 04 Mar 2018 05:41:29 +0000&lt;/pubDate&gt;\n &lt;dc:creator&gt;&lt;![CDATA[dave]]&gt;&lt;/dc:creator&gt;\n\n &lt;guid isPermaLink=\"false\"&gt;http://localhost/wp-theme-testing/?post_type=feature&amp;#038;p=3035&lt;/guid&gt;\n &lt;description&gt;&lt;![CDATA[a test!]]&gt;&lt;/description&gt;\n &lt;content:encoded&gt;&lt;![CDATA[&lt;p&gt;a test!&lt;/p&gt;\n]]&gt;&lt;/content:encoded&gt;\n &lt;wfw:commentRss&gt;http://localhost/wp-theme-testing/feartures/test-feature/feed/&lt;/wfw:commentRss&gt;\n &lt;slash:comments&gt;0&lt;/slash:comments&gt;\n &lt;/item&gt;\n &lt;/channel&gt;\n&lt;/rss&gt;\n</code></pre>\n" }, { "answer_id": 298119, "author": "William Turrell", "author_id": 42868, "author_profile": "https://wordpress.stackexchange.com/users/42868", "pm_score": 1, "selected": true, "text": "<p>This is a workaround, but it did solve things for me.</p>\n\n<p>First I moved this site from my vvv to vvv2 dev environment, to rule out anything odd there. Then I went through the WP config files and the rest of functions.php carefully looking for anything with the potential to break things. </p>\n\n<p>No luck so far.</p>\n\n<p>I traced <em>get_post_meta()</em> in the source, thinking I might only be able to solve this by rewriting an equivalent function myself (creating a DB query if necessary) - as readers may know it's simply a wrapper for <a href=\"https://developer.wordpress.org/reference/functions/get_metadata/\" rel=\"nofollow noreferrer\">get_metadata()</a> - for some reason this <em>does</em> work. </p>\n\n<p>So if anyone can suggest why get_post_meta() is undefined and get_metadata() isn't...</p>\n" } ]
2018/03/02
[ "https://wordpress.stackexchange.com/questions/295641", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137862/" ]
``` <title> <?php if ( is_single() ) { single_post_title('', true); } else { bloginfo('name'); echo " - "; bloginfo('description'); } ?> </title> ``` This is my title tag code used for my wordpress blog. But Seo analyst shows `No title tag` found error
This is a workaround, but it did solve things for me. First I moved this site from my vvv to vvv2 dev environment, to rule out anything odd there. Then I went through the WP config files and the rest of functions.php carefully looking for anything with the potential to break things. No luck so far. I traced *get\_post\_meta()* in the source, thinking I might only be able to solve this by rewriting an equivalent function myself (creating a DB query if necessary) - as readers may know it's simply a wrapper for [get\_metadata()](https://developer.wordpress.org/reference/functions/get_metadata/) - for some reason this *does* work. So if anyone can suggest why get\_post\_meta() is undefined and get\_metadata() isn't...
295,654
<p>I'm trying to find a way to not show all the terms of a taxonomy, but only the terms of the current displayed posts of the wp_query.</p> <p>The code below displays all terms for 'brands' taxonomy and the query displays all products of the current category, i want to display only the terms that are set on the products that are displaying.</p> <pre><code>$marcas_terms = get_terms([ 'taxonomy' =&gt; 'brands' ]); foreach ($brands_terms as $brand_term) { &lt;input type="checkbox" id="&lt;?php echo $brand_term-&gt;term_id; ?&gt;" name="marca" value="&lt;?php echo $brand_term-&gt;term_id; ?&gt;"&gt; &lt;label for="&lt;?php echo $brand_term-&gt;term_id; ?&gt;"&gt;&lt;?php echo $brand_term-&gt;name; ?&gt;&lt;/label&gt; } $args = array( 'post_type' =&gt; 'product', 'product_cat' =&gt; get_queried_object() ); $query = new WP_Query( $args ); if ( $query-&gt;have_posts() ) { while( $query-&gt;have_posts() ) : $query-&gt;the_post(); get_template_part("templates/product-content-category"); endwhile; } wp_reset_postdata(); </code></pre>
[ { "answer_id": 295668, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 2, "selected": false, "text": "<p>You'd probably do something like this </p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'product',\n 'product_cat' =&gt; get_queried_object()\n);\n$query = new WP_Query( $args );\n\n$termsInPosts = array();\nif ( $query-&gt;have_posts() ) {\n while( $query-&gt;have_posts() ) : $query-&gt;the_post();\n $postTerms = wp_get_post_terms(get_the_ID(), 'brands', array('fields' =&gt; 'term_id'));\n foreach ($postTerms as $postTerm)\n if (!in_array($postTerm-&gt;term_id, $termsInPosts))\n $termsInPosts[] = $postTerm-&gt;term_id;\n endwhile;\n} \n\n$marcas_terms = get_terms([\n 'taxonomy' =&gt; 'brands',\n 'include' =&gt; $termsInPosts\n]);\n\nforeach ($brands_terms as $brand_term) { \n &lt;input type=\"checkbox\" id=\"&lt;?php echo $brand_term-&gt;term_id; ?&gt;\" name=\"marca\" value=\"&lt;?php echo $brand_term-&gt;term_id; ?&gt;\"&gt;\n &lt;label for=\"&lt;?php echo $brand_term-&gt;term_id; ?&gt;\"&gt;&lt;?php echo $brand_term-&gt;name; ?&gt;&lt;/label&gt;\n}\n\nif ( $query-&gt;have_posts() ) {\n while( $query-&gt;have_posts() ) : $query-&gt;the_post();\n get_template_part(\"templates/product-content-category\");\n endwhile;\n} \n\nwp_reset_postdata(); \n</code></pre>\n\n<p>What you're doing is just running through the loop before hand, getting the id's of terms within the posts, adding to an array, then when you call <code>get_terms()</code> you're using <code>include</code> to include only the terms you found.</p>\n\n<p>I haven't tested this code, it's freehand, but it should work, or at least steer you in the right direction.</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 295690, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>I think we can simplify it with the <code>object_ids</code> argument of <code>get_terms()</code>, with post IDs plucked from the given posts array.</p>\n\n<p>Here's an untested skeleton, if I understand the problem correctly:</p>\n\n<pre><code>// Your post query\n$query = new WP_Query( $args );\n\nif( $query-&gt;have_posts() ) {\n\n // Get terms from the post IDs of the above post query\n $brand_terms = get_terms( [\n 'taxonomy' =&gt; 'brands',\n 'object_ids' =&gt; wp_list_pluck( $query-&gt;posts, 'ID' ),\n ] );\n\n // Your terms loop\n foreach ( $brands_terms as $brand_term ) { \n // ...\n }\n\n // Your posts loop\n while( $query-&gt;have_posts() ) { \n $query-&gt;the_post();\n get_template_part( \"templates/product-content-category\" );\n }\n\n wp_reset_postdata(); \n}\n</code></pre>\n\n<p>Hope it helps.</p>\n" } ]
2018/03/02
[ "https://wordpress.stackexchange.com/questions/295654", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111513/" ]
I'm trying to find a way to not show all the terms of a taxonomy, but only the terms of the current displayed posts of the wp\_query. The code below displays all terms for 'brands' taxonomy and the query displays all products of the current category, i want to display only the terms that are set on the products that are displaying. ``` $marcas_terms = get_terms([ 'taxonomy' => 'brands' ]); foreach ($brands_terms as $brand_term) { <input type="checkbox" id="<?php echo $brand_term->term_id; ?>" name="marca" value="<?php echo $brand_term->term_id; ?>"> <label for="<?php echo $brand_term->term_id; ?>"><?php echo $brand_term->name; ?></label> } $args = array( 'post_type' => 'product', 'product_cat' => get_queried_object() ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { while( $query->have_posts() ) : $query->the_post(); get_template_part("templates/product-content-category"); endwhile; } wp_reset_postdata(); ```
You'd probably do something like this ``` $args = array( 'post_type' => 'product', 'product_cat' => get_queried_object() ); $query = new WP_Query( $args ); $termsInPosts = array(); if ( $query->have_posts() ) { while( $query->have_posts() ) : $query->the_post(); $postTerms = wp_get_post_terms(get_the_ID(), 'brands', array('fields' => 'term_id')); foreach ($postTerms as $postTerm) if (!in_array($postTerm->term_id, $termsInPosts)) $termsInPosts[] = $postTerm->term_id; endwhile; } $marcas_terms = get_terms([ 'taxonomy' => 'brands', 'include' => $termsInPosts ]); foreach ($brands_terms as $brand_term) { <input type="checkbox" id="<?php echo $brand_term->term_id; ?>" name="marca" value="<?php echo $brand_term->term_id; ?>"> <label for="<?php echo $brand_term->term_id; ?>"><?php echo $brand_term->name; ?></label> } if ( $query->have_posts() ) { while( $query->have_posts() ) : $query->the_post(); get_template_part("templates/product-content-category"); endwhile; } wp_reset_postdata(); ``` What you're doing is just running through the loop before hand, getting the id's of terms within the posts, adding to an array, then when you call `get_terms()` you're using `include` to include only the terms you found. I haven't tested this code, it's freehand, but it should work, or at least steer you in the right direction. Hope that helps.
295,693
<p>I want to get a list of products of a given category from WP_query, but it won't work like it should.</p> <p>I've done this :</p> <pre><code>$args = array( 'post_type' =&gt; 'product', 'product_cat' =&gt; 17, ); $products = new WP_Query($args); </code></pre> <p>But this returns <strong>every</strong> product from my shop ... I have also tried with 'cat', 'category' and 'category_name' attr with same result.</p> <p>I've tried using tax_query :</p> <pre><code>$args = array( 'post_type' =&gt; 'product', 'tax_query' =&gt; array( 'taxonomy' =&gt; 'product_cat', 'terms' =&gt; 17 ), ); $products = new WP_Query($args); </code></pre> <p>And this also returns <strong>every products</strong> I have also tried with 'cat', 'category' and 'category_name' with same result.</p> <p>I have managed using the following code to get regular posts from a given category.</p> <pre><code>$args = array( 'post_type' =&gt; 'post', 'cat' =&gt; 22 ); $posts = new WP_Query($args); </code></pre> <p>A couple more things :</p> <ul> <li>I am certain I have the right category id.</li> <li>tax_query worked for the posts too</li> <li><p>edit : <code>tax_query</code> returns every products, ignoring my <code>product_cat</code> attr</p> <p>I have been looking to do this for days and tried every possible solution of similar questions on stack and other sites without success... Why doesn't it work for products ?</p></li> </ul> <p>EDIT : the code snipet with <code>tax_query</code> was wrong so I changed it.</p> <p>EDIT 2 : I have tried several new Things, here is the summary :</p> <ul> <li>disabled all custom hooks : same results</li> <li>instantiated a <code>WC_Product</code> manually by the id of an actual product as an argument. It shows that its <code>category_ids</code> attribute is empty, even though the product <em>does</em> have a category on the admin panel... and the category taxonomy page shows the right stuff too.</li> <li>when I do <code>var_dump(get_the_terms($postID, 'category'));</code> on a regular post it works fine</li> </ul> <p>EDIT 3 : - disabled all plugins but Woocommerce with same result... - when I do <code>var_dump(get_post_types());</code>, the product post type does not show. And so naturally, when I do <code>var_dump(get_object_taxonomies('product'));</code>, it returns an empty array.</p>
[ { "answer_id": 295668, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 2, "selected": false, "text": "<p>You'd probably do something like this </p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'product',\n 'product_cat' =&gt; get_queried_object()\n);\n$query = new WP_Query( $args );\n\n$termsInPosts = array();\nif ( $query-&gt;have_posts() ) {\n while( $query-&gt;have_posts() ) : $query-&gt;the_post();\n $postTerms = wp_get_post_terms(get_the_ID(), 'brands', array('fields' =&gt; 'term_id'));\n foreach ($postTerms as $postTerm)\n if (!in_array($postTerm-&gt;term_id, $termsInPosts))\n $termsInPosts[] = $postTerm-&gt;term_id;\n endwhile;\n} \n\n$marcas_terms = get_terms([\n 'taxonomy' =&gt; 'brands',\n 'include' =&gt; $termsInPosts\n]);\n\nforeach ($brands_terms as $brand_term) { \n &lt;input type=\"checkbox\" id=\"&lt;?php echo $brand_term-&gt;term_id; ?&gt;\" name=\"marca\" value=\"&lt;?php echo $brand_term-&gt;term_id; ?&gt;\"&gt;\n &lt;label for=\"&lt;?php echo $brand_term-&gt;term_id; ?&gt;\"&gt;&lt;?php echo $brand_term-&gt;name; ?&gt;&lt;/label&gt;\n}\n\nif ( $query-&gt;have_posts() ) {\n while( $query-&gt;have_posts() ) : $query-&gt;the_post();\n get_template_part(\"templates/product-content-category\");\n endwhile;\n} \n\nwp_reset_postdata(); \n</code></pre>\n\n<p>What you're doing is just running through the loop before hand, getting the id's of terms within the posts, adding to an array, then when you call <code>get_terms()</code> you're using <code>include</code> to include only the terms you found.</p>\n\n<p>I haven't tested this code, it's freehand, but it should work, or at least steer you in the right direction.</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 295690, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>I think we can simplify it with the <code>object_ids</code> argument of <code>get_terms()</code>, with post IDs plucked from the given posts array.</p>\n\n<p>Here's an untested skeleton, if I understand the problem correctly:</p>\n\n<pre><code>// Your post query\n$query = new WP_Query( $args );\n\nif( $query-&gt;have_posts() ) {\n\n // Get terms from the post IDs of the above post query\n $brand_terms = get_terms( [\n 'taxonomy' =&gt; 'brands',\n 'object_ids' =&gt; wp_list_pluck( $query-&gt;posts, 'ID' ),\n ] );\n\n // Your terms loop\n foreach ( $brands_terms as $brand_term ) { \n // ...\n }\n\n // Your posts loop\n while( $query-&gt;have_posts() ) { \n $query-&gt;the_post();\n get_template_part( \"templates/product-content-category\" );\n }\n\n wp_reset_postdata(); \n}\n</code></pre>\n\n<p>Hope it helps.</p>\n" } ]
2018/03/03
[ "https://wordpress.stackexchange.com/questions/295693", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112695/" ]
I want to get a list of products of a given category from WP\_query, but it won't work like it should. I've done this : ``` $args = array( 'post_type' => 'product', 'product_cat' => 17, ); $products = new WP_Query($args); ``` But this returns **every** product from my shop ... I have also tried with 'cat', 'category' and 'category\_name' attr with same result. I've tried using tax\_query : ``` $args = array( 'post_type' => 'product', 'tax_query' => array( 'taxonomy' => 'product_cat', 'terms' => 17 ), ); $products = new WP_Query($args); ``` And this also returns **every products** I have also tried with 'cat', 'category' and 'category\_name' with same result. I have managed using the following code to get regular posts from a given category. ``` $args = array( 'post_type' => 'post', 'cat' => 22 ); $posts = new WP_Query($args); ``` A couple more things : * I am certain I have the right category id. * tax\_query worked for the posts too * edit : `tax_query` returns every products, ignoring my `product_cat` attr I have been looking to do this for days and tried every possible solution of similar questions on stack and other sites without success... Why doesn't it work for products ? EDIT : the code snipet with `tax_query` was wrong so I changed it. EDIT 2 : I have tried several new Things, here is the summary : * disabled all custom hooks : same results * instantiated a `WC_Product` manually by the id of an actual product as an argument. It shows that its `category_ids` attribute is empty, even though the product *does* have a category on the admin panel... and the category taxonomy page shows the right stuff too. * when I do `var_dump(get_the_terms($postID, 'category'));` on a regular post it works fine EDIT 3 : - disabled all plugins but Woocommerce with same result... - when I do `var_dump(get_post_types());`, the product post type does not show. And so naturally, when I do `var_dump(get_object_taxonomies('product'));`, it returns an empty array.
You'd probably do something like this ``` $args = array( 'post_type' => 'product', 'product_cat' => get_queried_object() ); $query = new WP_Query( $args ); $termsInPosts = array(); if ( $query->have_posts() ) { while( $query->have_posts() ) : $query->the_post(); $postTerms = wp_get_post_terms(get_the_ID(), 'brands', array('fields' => 'term_id')); foreach ($postTerms as $postTerm) if (!in_array($postTerm->term_id, $termsInPosts)) $termsInPosts[] = $postTerm->term_id; endwhile; } $marcas_terms = get_terms([ 'taxonomy' => 'brands', 'include' => $termsInPosts ]); foreach ($brands_terms as $brand_term) { <input type="checkbox" id="<?php echo $brand_term->term_id; ?>" name="marca" value="<?php echo $brand_term->term_id; ?>"> <label for="<?php echo $brand_term->term_id; ?>"><?php echo $brand_term->name; ?></label> } if ( $query->have_posts() ) { while( $query->have_posts() ) : $query->the_post(); get_template_part("templates/product-content-category"); endwhile; } wp_reset_postdata(); ``` What you're doing is just running through the loop before hand, getting the id's of terms within the posts, adding to an array, then when you call `get_terms()` you're using `include` to include only the terms you found. I haven't tested this code, it's freehand, but it should work, or at least steer you in the right direction. Hope that helps.
295,714
<p>Is it possible to override single plugin translation in function.php file and how that can be done?</p>
[ { "answer_id": 295729, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": false, "text": "<p>Here's an example where a string from a certain text domain is translated using the <code>gettext</code> filter:</p>\n\n<pre><code>/**\n * Translate a certain string from a particular text domain.\n *\n * @param string $translation Translated text.\n * @param string $text Text to translate.\n * @param string $domain Text domain. Unique identifier for retrieving translated strings.\n *\n * @return string\n */\nadd_filter( 'gettext', 'wpse_translate_string', 10, 3 );\nfunction wpse_translate_string( $translation, $text, $domain ) {\n if ( 'plugin_text_domain' === $domain ) {\n if ( 'Original string...' === $text ) {\n $translation = 'New string!';\n }\n }\n\n return $translation;\n}\n</code></pre>\n" }, { "answer_id": 314293, "author": "brenorb", "author_id": 150710, "author_profile": "https://wordpress.stackexchange.com/users/150710", "pm_score": 0, "selected": false, "text": "<p>You can even override single messages if you go directly to your source code.</p>\n\n<pre><code>function foo(){\n // old message is commented, so you can go back anytime.\n //echo wp_send_json(array('status' =&gt; 'error', 'error_message' =&gt; esc_html__('Error Message', 'osetin')));\n // message is overriden \n echo wp_send_json(array('status' =&gt; 'error', 'error_message' =&gt; esc_html__('Overriden message with any text you want', 'osetin')));\n}\n</code></pre>\n" }, { "answer_id": 402563, "author": "Saeed", "author_id": 143910, "author_profile": "https://wordpress.stackexchange.com/users/143910", "pm_score": 1, "selected": false, "text": "<p>The best approach is overriding translation file .po</p>\n<pre><code>add_filter( 'load_textdomain_mofile', 'load_custom_plugin_translation_file', 10, 2 );\nfunction load_custom_plugin_translation_file( $mofile, $domain ) {\n if ('woocommerce' === $domain) {\n $mofile = get_stylesheet_directory() . '/languages/woocommerce-' . get_locale() . '.mo';\n }\n return $mofile;\n}\n</code></pre>\n" } ]
2018/03/03
[ "https://wordpress.stackexchange.com/questions/295714", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92020/" ]
Is it possible to override single plugin translation in function.php file and how that can be done?
Here's an example where a string from a certain text domain is translated using the `gettext` filter: ``` /** * Translate a certain string from a particular text domain. * * @param string $translation Translated text. * @param string $text Text to translate. * @param string $domain Text domain. Unique identifier for retrieving translated strings. * * @return string */ add_filter( 'gettext', 'wpse_translate_string', 10, 3 ); function wpse_translate_string( $translation, $text, $domain ) { if ( 'plugin_text_domain' === $domain ) { if ( 'Original string...' === $text ) { $translation = 'New string!'; } } return $translation; } ```
295,734
<p>the thing is that in mobile/tabler versions blank white space appears. In desktop version there is no such problem. Moreover, I noticed that if you drag something in mobile version from that blank space, it appears to be a logo from header. I would appreciate any help. My website: www.avizen.lt</p>
[ { "answer_id": 295729, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": false, "text": "<p>Here's an example where a string from a certain text domain is translated using the <code>gettext</code> filter:</p>\n\n<pre><code>/**\n * Translate a certain string from a particular text domain.\n *\n * @param string $translation Translated text.\n * @param string $text Text to translate.\n * @param string $domain Text domain. Unique identifier for retrieving translated strings.\n *\n * @return string\n */\nadd_filter( 'gettext', 'wpse_translate_string', 10, 3 );\nfunction wpse_translate_string( $translation, $text, $domain ) {\n if ( 'plugin_text_domain' === $domain ) {\n if ( 'Original string...' === $text ) {\n $translation = 'New string!';\n }\n }\n\n return $translation;\n}\n</code></pre>\n" }, { "answer_id": 314293, "author": "brenorb", "author_id": 150710, "author_profile": "https://wordpress.stackexchange.com/users/150710", "pm_score": 0, "selected": false, "text": "<p>You can even override single messages if you go directly to your source code.</p>\n\n<pre><code>function foo(){\n // old message is commented, so you can go back anytime.\n //echo wp_send_json(array('status' =&gt; 'error', 'error_message' =&gt; esc_html__('Error Message', 'osetin')));\n // message is overriden \n echo wp_send_json(array('status' =&gt; 'error', 'error_message' =&gt; esc_html__('Overriden message with any text you want', 'osetin')));\n}\n</code></pre>\n" }, { "answer_id": 402563, "author": "Saeed", "author_id": 143910, "author_profile": "https://wordpress.stackexchange.com/users/143910", "pm_score": 1, "selected": false, "text": "<p>The best approach is overriding translation file .po</p>\n<pre><code>add_filter( 'load_textdomain_mofile', 'load_custom_plugin_translation_file', 10, 2 );\nfunction load_custom_plugin_translation_file( $mofile, $domain ) {\n if ('woocommerce' === $domain) {\n $mofile = get_stylesheet_directory() . '/languages/woocommerce-' . get_locale() . '.mo';\n }\n return $mofile;\n}\n</code></pre>\n" } ]
2018/03/04
[ "https://wordpress.stackexchange.com/questions/295734", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137935/" ]
the thing is that in mobile/tabler versions blank white space appears. In desktop version there is no such problem. Moreover, I noticed that if you drag something in mobile version from that blank space, it appears to be a logo from header. I would appreciate any help. My website: www.avizen.lt
Here's an example where a string from a certain text domain is translated using the `gettext` filter: ``` /** * Translate a certain string from a particular text domain. * * @param string $translation Translated text. * @param string $text Text to translate. * @param string $domain Text domain. Unique identifier for retrieving translated strings. * * @return string */ add_filter( 'gettext', 'wpse_translate_string', 10, 3 ); function wpse_translate_string( $translation, $text, $domain ) { if ( 'plugin_text_domain' === $domain ) { if ( 'Original string...' === $text ) { $translation = 'New string!'; } } return $translation; } ```
295,741
<p>I'm trying to display the get_category_category limiting the results to only the child categories of parent "666". </p> <p>So a post may have a number of categories e.g. "1234", "666", "666/1341", "5", "5/17" but I only want to show the child of "666".</p> <pre><code>$args = array( 'numberposts' =&gt; '5','post_status' =&gt; 'publish','category' =&gt; '1234','category__not_in' =&gt; '680', 'orderby' =&gt; 'post_date', 'order' =&gt; 'DESC' ); $recent_posts = wp_get_recent_posts($args); { ///I want to return the category for each post in this loop that is within the "666" category. ///E.g get_the_category($recent['ID']) where the category is a child of 666 echo "POST ID" . $recent['ID'] . " CHILD CATEGORY ". $childcategory; } </code></pre> <p>The above loop will return the last 5 posts in category "1234" with each child category of "666".</p> <p>e.g. </p> <ul> <li>POST ID 10 CHILD CATEGORY 1341</li> <li>POST ID 11 CHILD CATEGORY 1341</li> <li>POST ID 14 CHILD CATEGORY 99</li> <li>POST ID 19 CHILD CATEGORY 1341</li> <li>POST ID 23 CHILD CATEGORY 99</li> </ul>
[ { "answer_id": 295742, "author": "admcfajn", "author_id": 123674, "author_profile": "https://wordpress.stackexchange.com/users/123674", "pm_score": 1, "selected": false, "text": "<p>You can do this by getting the child categories of that category first, then passing them as an array to your query.</p>\n\n<pre><code>$categories=get_categories(\n array( 'parent' =&gt; $cat-&gt;cat_ID )\n);\n\n$cat_list = [];\nforeach ($categories as $c) {\n $cat_list[] = $c-&gt;term_id;\n}\n</code></pre>\n\n<p>ref: <a href=\"https://wordpress.stackexchange.com/questions/74345/get-the-children-of-the-parent-category\">Get the children of the parent category</a></p>\n\n<p>This won't/might not work, but it's usually worth trying passing an array where you could pass an integer in WordPress:</p>\n\n<pre><code>$args = array( 'numberposts' =&gt; '5','post_status' =&gt; 'publish','category' =&gt; $cat_list,'category__not_in' =&gt; '680', 'orderby' =&gt; 'post_date', 'order' =&gt; 'DESC' );\n</code></pre>\n\n<p><code>wp_get_recent_posts</code> uses <code>get_posts</code> &amp; <code>get_post</code> accepts an ID of a category, at the time of writing it doesn't mention an array... So you might need to use <code>WP_Query</code>:</p>\n\n<pre><code>$query = new WP_Query( array( 'category__and' =&gt; $cat_list ) );\n</code></pre>\n\n<p>see: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query</a></p>\n" }, { "answer_id": 317973, "author": "Meriton Reqica", "author_id": 153245, "author_profile": "https://wordpress.stackexchange.com/users/153245", "pm_score": 0, "selected": false, "text": "<p>You can use <code>array_map</code> so you can return only the categories that you want. For example:</p>\n\n<pre><code>array_map( function( $cat ) {\n if ( $cat-&gt;parent != 0 ) {\n return $cat;\n }\n },\n get_the_category()\n);\n</code></pre>\n" } ]
2018/03/04
[ "https://wordpress.stackexchange.com/questions/295741", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137938/" ]
I'm trying to display the get\_category\_category limiting the results to only the child categories of parent "666". So a post may have a number of categories e.g. "1234", "666", "666/1341", "5", "5/17" but I only want to show the child of "666". ``` $args = array( 'numberposts' => '5','post_status' => 'publish','category' => '1234','category__not_in' => '680', 'orderby' => 'post_date', 'order' => 'DESC' ); $recent_posts = wp_get_recent_posts($args); { ///I want to return the category for each post in this loop that is within the "666" category. ///E.g get_the_category($recent['ID']) where the category is a child of 666 echo "POST ID" . $recent['ID'] . " CHILD CATEGORY ". $childcategory; } ``` The above loop will return the last 5 posts in category "1234" with each child category of "666". e.g. * POST ID 10 CHILD CATEGORY 1341 * POST ID 11 CHILD CATEGORY 1341 * POST ID 14 CHILD CATEGORY 99 * POST ID 19 CHILD CATEGORY 1341 * POST ID 23 CHILD CATEGORY 99
You can do this by getting the child categories of that category first, then passing them as an array to your query. ``` $categories=get_categories( array( 'parent' => $cat->cat_ID ) ); $cat_list = []; foreach ($categories as $c) { $cat_list[] = $c->term_id; } ``` ref: [Get the children of the parent category](https://wordpress.stackexchange.com/questions/74345/get-the-children-of-the-parent-category) This won't/might not work, but it's usually worth trying passing an array where you could pass an integer in WordPress: ``` $args = array( 'numberposts' => '5','post_status' => 'publish','category' => $cat_list,'category__not_in' => '680', 'orderby' => 'post_date', 'order' => 'DESC' ); ``` `wp_get_recent_posts` uses `get_posts` & `get_post` accepts an ID of a category, at the time of writing it doesn't mention an array... So you might need to use `WP_Query`: ``` $query = new WP_Query( array( 'category__and' => $cat_list ) ); ``` see: <https://codex.wordpress.org/Class_Reference/WP_Query>
295,879
<p>I want to use this:</p> <pre><code>http://www.example.com/directory/alan-walker </code></pre> <p>instead of calling <code>alan-walker.php</code> (which is non-existent) it should call <code>directory.php?s=alan-walker</code></p> <p>Is this possible?</p> <p>I suspect it's the <code>.htaccess</code> rewrite no?</p> <p>Effectively what this does is it means I can use this:</p> <pre><code>/directory/alan-walker (good) </code></pre> <p>instead of</p> <pre><code>directory?s=alan-walker (bad) </code></pre>
[ { "answer_id": 295931, "author": "Ravi Patel", "author_id": 35477, "author_profile": "https://wordpress.stackexchange.com/users/35477", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p><strong>Change the Search-URL of WordPress - Add code in function.php and customize with directory</strong></p>\n</blockquote>\n\n<pre><code>function fb_change_search_url_rewrite() {\n if ( is_search() &amp;&amp; ! empty( $_GET['s'] ) ) {\n wp_redirect( home_url( \"/search/\" ) . urlencode( get_query_var( 's' ) ) );\n exit();\n } \n}\nadd_action( 'template_redirect', 'fb_change_search_url_rewrite' );\n</code></pre>\n\n<p><strong>Yes, it is also possible via htacces rules, but the source is an example for custom solutions on an redirect.</strong></p>\n\n<pre><code># search redirect\n# this will take anything in the query string, minus any extraneous values, and turn them into a clean working url\nRewriteCond %{QUERY_STRING} \\\\?s=([^&amp;]+) [NC]\nRewriteRule ^$ /search/%1/? [NC,R,L]\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/UfHXF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UfHXF.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 295958, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 1, "selected": false, "text": "<p>I assume <code>alan-walker</code> is just an example and this could be any string of this form. (Or is it literally just \"alan-walker\", as in you example?)</p>\n\n<p>You can do this with a single <code>RewriteRule</code> in <code>.htaccess</code> <em>before</em> the WordPress front-controller. For example:</p>\n\n<pre><code>RewriteRule ^directory/([a-z-]+)$ /directory.php?s=$1 [L]\n</code></pre>\n\n<p>This will rewrite <code>/directory/&lt;something&gt;</code> to <code>/directory.php?s=&lt;something&gt;</code>,\n where <code>&lt;something&gt;</code> consists of one or more of the characters <code>a</code> to <code>z</code> and <code>-</code>.</p>\n\n<hr>\n\n<blockquote>\n <p>...instead of calling alan-walker.php</p>\n</blockquote>\n\n<p>This would only happen if you have MultiViews enabled. And only if <code>alan-walker.php</code> existed as a real file (which you say it doesn't). It is not enabled by default, however, if it is, it can be disabled by calling the following at the top of your <code>.htaccess</code> file:</p>\n\n<pre><code>Options -MultiViews\n</code></pre>\n" } ]
2018/03/05
[ "https://wordpress.stackexchange.com/questions/295879", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137938/" ]
I want to use this: ``` http://www.example.com/directory/alan-walker ``` instead of calling `alan-walker.php` (which is non-existent) it should call `directory.php?s=alan-walker` Is this possible? I suspect it's the `.htaccess` rewrite no? Effectively what this does is it means I can use this: ``` /directory/alan-walker (good) ``` instead of ``` directory?s=alan-walker (bad) ```
I assume `alan-walker` is just an example and this could be any string of this form. (Or is it literally just "alan-walker", as in you example?) You can do this with a single `RewriteRule` in `.htaccess` *before* the WordPress front-controller. For example: ``` RewriteRule ^directory/([a-z-]+)$ /directory.php?s=$1 [L] ``` This will rewrite `/directory/<something>` to `/directory.php?s=<something>`, where `<something>` consists of one or more of the characters `a` to `z` and `-`. --- > > ...instead of calling alan-walker.php > > > This would only happen if you have MultiViews enabled. And only if `alan-walker.php` existed as a real file (which you say it doesn't). It is not enabled by default, however, if it is, it can be disabled by calling the following at the top of your `.htaccess` file: ``` Options -MultiViews ```
295,910
<p>I have put this code inside PHP file and put that file in root folder. When I run this file it Create "Admin" user for only main site. I want code that will create "super admin" which can access all the multi-site. </p> <pre><code>require ('wp-blog-header.php'); $newusername = 'USERNAME'; $newpassword = 'PASSWORD'; $newemail = 'EMAIL'; if ($newpassword != ' ' &amp;&amp; $newemail != ' ' &amp;&amp; $newusername != ' ') { if (!username_exists($newusername) &amp;&amp; !email_exists($newemail)) { $user_id = wp_create_user($newusername, $newpassword, $newemail); if (is_int($user_id)) { $wp_user_object = new WP_User($user_id); $wp_user_object-&gt;set_role('administrator'); echo 'Successfully created new admin user.'; } else { echo 'Error with wp_insert_user. No users were created.'; } } else { echo 'This user or email already exists. Nothing was done.'; } } else { echo "Whoops, looks like you didn't set a password, username, or email before running the script. Set these variables and try again."; } </code></pre>
[ { "answer_id": 295931, "author": "Ravi Patel", "author_id": 35477, "author_profile": "https://wordpress.stackexchange.com/users/35477", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p><strong>Change the Search-URL of WordPress - Add code in function.php and customize with directory</strong></p>\n</blockquote>\n\n<pre><code>function fb_change_search_url_rewrite() {\n if ( is_search() &amp;&amp; ! empty( $_GET['s'] ) ) {\n wp_redirect( home_url( \"/search/\" ) . urlencode( get_query_var( 's' ) ) );\n exit();\n } \n}\nadd_action( 'template_redirect', 'fb_change_search_url_rewrite' );\n</code></pre>\n\n<p><strong>Yes, it is also possible via htacces rules, but the source is an example for custom solutions on an redirect.</strong></p>\n\n<pre><code># search redirect\n# this will take anything in the query string, minus any extraneous values, and turn them into a clean working url\nRewriteCond %{QUERY_STRING} \\\\?s=([^&amp;]+) [NC]\nRewriteRule ^$ /search/%1/? [NC,R,L]\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/UfHXF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UfHXF.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 295958, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 1, "selected": false, "text": "<p>I assume <code>alan-walker</code> is just an example and this could be any string of this form. (Or is it literally just \"alan-walker\", as in you example?)</p>\n\n<p>You can do this with a single <code>RewriteRule</code> in <code>.htaccess</code> <em>before</em> the WordPress front-controller. For example:</p>\n\n<pre><code>RewriteRule ^directory/([a-z-]+)$ /directory.php?s=$1 [L]\n</code></pre>\n\n<p>This will rewrite <code>/directory/&lt;something&gt;</code> to <code>/directory.php?s=&lt;something&gt;</code>,\n where <code>&lt;something&gt;</code> consists of one or more of the characters <code>a</code> to <code>z</code> and <code>-</code>.</p>\n\n<hr>\n\n<blockquote>\n <p>...instead of calling alan-walker.php</p>\n</blockquote>\n\n<p>This would only happen if you have MultiViews enabled. And only if <code>alan-walker.php</code> existed as a real file (which you say it doesn't). It is not enabled by default, however, if it is, it can be disabled by calling the following at the top of your <code>.htaccess</code> file:</p>\n\n<pre><code>Options -MultiViews\n</code></pre>\n" } ]
2018/03/06
[ "https://wordpress.stackexchange.com/questions/295910", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110795/" ]
I have put this code inside PHP file and put that file in root folder. When I run this file it Create "Admin" user for only main site. I want code that will create "super admin" which can access all the multi-site. ``` require ('wp-blog-header.php'); $newusername = 'USERNAME'; $newpassword = 'PASSWORD'; $newemail = 'EMAIL'; if ($newpassword != ' ' && $newemail != ' ' && $newusername != ' ') { if (!username_exists($newusername) && !email_exists($newemail)) { $user_id = wp_create_user($newusername, $newpassword, $newemail); if (is_int($user_id)) { $wp_user_object = new WP_User($user_id); $wp_user_object->set_role('administrator'); echo 'Successfully created new admin user.'; } else { echo 'Error with wp_insert_user. No users were created.'; } } else { echo 'This user or email already exists. Nothing was done.'; } } else { echo "Whoops, looks like you didn't set a password, username, or email before running the script. Set these variables and try again."; } ```
I assume `alan-walker` is just an example and this could be any string of this form. (Or is it literally just "alan-walker", as in you example?) You can do this with a single `RewriteRule` in `.htaccess` *before* the WordPress front-controller. For example: ``` RewriteRule ^directory/([a-z-]+)$ /directory.php?s=$1 [L] ``` This will rewrite `/directory/<something>` to `/directory.php?s=<something>`, where `<something>` consists of one or more of the characters `a` to `z` and `-`. --- > > ...instead of calling alan-walker.php > > > This would only happen if you have MultiViews enabled. And only if `alan-walker.php` existed as a real file (which you say it doesn't). It is not enabled by default, however, if it is, it can be disabled by calling the following at the top of your `.htaccess` file: ``` Options -MultiViews ```
295,912
<p>Please note that, I'm not telling about conditionally enqueue/dequeue scripts, I'm referring to conditionally dequeue certain dependencies from an existing enqueued scripts in front end. And please note the question is not plugin-specific. I want to be enlightened about the general rules.</p> <p>I used Elementor (page builder) for front end. But it's not used in all my pages. So the default lightbox feature enabled in Elementor doesn't work in those pages. That's why I added <a href="https://github.com/fancyapps/fancybox/" rel="nofollow noreferrer">my own lightbox</a> throughout the site, using a regex <code>$pattern ="/&lt;a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)&gt;/i";</code> hooked to the <code>the_content</code> filter. Thing's working fine, but-</p> <p>Where there the Elementor gallery or lightbox is triggered, both the scripts are messing up. Two lightbox are being called, sometimes the gallery lightbox are conflicting and not working etc.</p> <h2>Solution 1:</h2> <p>I know I can conditionally filter <code>the_content</code> with the regex like:</p> <pre><code>if( ! is_singular('cpt') ) { return $content = preg_replace($pattern, $replacement, $content); } </code></pre> <p>But I actually want to keep this feature everywhere. Just want to remove the elementor lightbox where I want 'em to. So, I's trying the solution#2.</p> <h2>Solution 2:</h2> <p>What Elementor did, is something, <em>like</em>:</p> <pre><code>wp_enqueue_script('elementor-frontend', 'link/to/frontend.js', array('elementor-dialog', 'elementor-waypoints', 'jquery-swiper'), '1.9.7', true); </code></pre> <p>Now I want not to load the lightbox feature from Elementor, so I tried to dequeue the <code>'elementor-dialog'</code>:</p> <pre><code>if( is_singular('cpt') ) { wp_dequeue_script( 'elementor-dialog' ); } </code></pre> <p>But it's not working, as the dependencies are set in <code>'elementor-frontend'</code>. So I tried deregistering dialog:</p> <pre><code>if( is_singular('cpt') ) { wp_dequeue_script( 'elementor-dialog' ); wp_deregister_script( 'elementor-dialog' ); } </code></pre> <p>It's devastating, because it dequeued the <code>frontend.js</code>.</p> <p>How can I change the dependencies of <code>frontend.js</code> (handle: <code>'elementor-frontend'</code>) on the fly, so that I can change the dependencies to <code>array('elementor-waypoints', 'jquery-swiper')</code>?</p>
[ { "answer_id": 295935, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<h2>Solution 1:</h2>\n\n<p>Here we will dequeue and deregister <code>elementor-dialog</code> <em>and</em> <code>elementor-frontend</code>, then we will re-register <code>elementor-frontend</code> without the <code>elementor-dialog</code> dependency:</p>\n\n<pre><code>// This needs to fire after priority 5 which is where Elementor\n// handles enqueueing scripts. We're ok since the default is 10.\nadd_action( 'wp_enqueue_scripts', 'wpse_elementor_frontend_scripts' );\nfunction wpse_elementor_frontend_scripts() {\n // Optionally add guard clauses such as checking if( ! is_singular('cpt') )...\n\n // Bail if Elementor is not available.\n if ( ! defined( 'ELEMENTOR_VERSION' ) ) {\n return;\n }\n\n // Dequeue and deregister elementor-dialog\n wp_dequeue_script( 'elementor-dialog' );\n wp_deregister_script( 'elementor-dialog' );\n\n // Dequeue and deregister elementor-frontend\n wp_dequeue_script( 'elementor-frontend' );\n wp_deregister_script( 'elementor-frontend' );\n\n // Re-register elementor-frontend without the elementor-dialog dependency.\n $suffix = ( defined( 'SCRIPT_DEBUG' ) &amp;&amp; SCRIPT_DEBUG ) ? '' : '.min';\n wp_register_script(\n 'elementor-frontend',\n ELEMENTOR_ASSETS_URL . 'js/frontend' . $suffix . '.js',\n [\n //'elementor-dialog', // &lt;-- We removed this\n 'elementor-waypoints',\n 'jquery-swiper',\n ],\n ELEMENTOR_VERSION,\n true\n );\n\n // debugging... \n //$scripts = wp_scripts();\n //exit ( print_r( $scripts ) );\n}\n</code></pre>\n\n<h2>Solution 2:</h2>\n\n<p>In this solution, we will use <code>wp_scripts()</code> to modify the <code>$wp_scripts</code> global and then safely deregister <code>elementor-dialog</code>.</p>\n\n<p>We will remove the <code>elementor-dialog</code> dependency from the <code>elementor-frontend</code> handle, then dequeue the <code>elementor-dialog</code> script which is enqueued separately by the <code>Elementor\\Frontend</code> class.</p>\n\n<pre><code>/**\n * The Elementor\\Frontend class runs its register_scripts() method on\n * wp_enqueue_scripts at priority 5, so we want to hook in after this has taken place.\n */\nadd_action( 'wp_enqueue_scripts', 'wpse_elementor_frontend_scripts_modifier', 6 );\nfunction wpse_elementor_frontend_scripts_modifier() {\n\n // Customize guard clauses to bail if we don't want to run this code.\n /*if ( ! is_singular( 'cpt' ) ) {\n return;\n }*/\n\n // Get all scripts.\n $scripts = wp_scripts();\n\n // Bail if something went wrong.\n if ( ! ( $scripts instanceof WP_Scripts ) ) {\n return;\n }\n\n // Array of handles to remove.\n $handles_to_remove = [\n 'elementor-dialog',\n ];\n\n // Flag indicating if we have removed the handles.\n $handles_updated = false;\n\n // Remove desired handles from the elementor-frontend script. \n foreach ( $scripts-&gt;registered as $dependency_object_id =&gt; $dependency_object ) {\n\n if ( 'elementor-frontend' === $dependency_object_id ) {\n\n // Bail if something went wrong.\n if ( ! ( $dependency_object instanceof _WP_Dependency ) ) {\n return;\n }\n\n // Bail if there are no dependencies for some reason.\n if ( empty( $dependency_object-&gt;deps ) ) {\n return;\n }\n\n // Do the handle removal.\n foreach ( $dependency_object-&gt;deps as $dep_key =&gt; $handle ) {\n if ( in_array( $handle, $handles_to_remove ) ) {\n unset( $dependency_object-&gt;deps[ $dep_key ] );\n $dependency_object-&gt;deps = array_values( $dependency_object-&gt;deps ); // \"reindex\" array\n $handles_updated = true;\n }\n }\n }\n }\n\n // If we have updated the handles, dequeue the relevant dependencies which\n // were enqueued separately Elementor\\Frontend.\n if ( $handles_updated ) {\n wp_dequeue_script( 'elementor-dialog' );\n wp_deregister_script( 'elementor-dialog' );\n }\n}\n</code></pre>\n\n<p>By modifying <code>elementor-frontend</code> before dequeueing <code>elementor-dialog</code>, we will not unintentionally dequeue <code>elementor-frontend</code> when we dequeue <code>elementor-dialog</code>.</p>\n\n<p>When testing this code, I inspected the <code>$wp_scripts</code> global (via <code>wp_scripts()</code>) to ensure that the desired results took effect. E.g.</p>\n\n<pre><code>$scripts = wp_scripts();\nprint_r( $scripts ); \n</code></pre>\n\n<p><strong>Relevant part of <code>$scripts</code> before modification:</strong></p>\n\n<pre><code>...\n\n[elementor-dialog] =&gt; _WP_Dependency Object\n(\n [handle] =&gt; elementor-dialog\n [src] =&gt; http://example.com/wp-content/plugins/elementor/assets/lib/dialog/dialog.js\n [deps] =&gt; Array\n (\n [0] =&gt; jquery-ui-position\n )\n\n [ver] =&gt; 4.1.0\n [args] =&gt; \n [extra] =&gt; Array\n (\n [group] =&gt; 1\n )\n\n)\n\n[elementor-frontend] =&gt; _WP_Dependency Object\n(\n [handle] =&gt; elementor-frontend\n [src] =&gt; http://example.com/wp-content/plugins/elementor/assets/js/frontend.js\n [deps] =&gt; Array\n (\n [0] =&gt; elementor-dialog\n [1] =&gt; elementor-waypoints\n [2] =&gt; jquery-swiper\n )\n\n [ver] =&gt; 1.9.7\n [args] =&gt; \n [extra] =&gt; Array\n (\n [group] =&gt; 1\n )\n\n)\n\n...\n</code></pre>\n\n<p><strong>Relevant part of <code>$scripts</code> after modification:</strong></p>\n\n<p>(Note that the <code>elementor-dialog</code> node has now been removed.)</p>\n\n<pre><code>...\n[elementor-frontend] =&gt; _WP_Dependency Object\n(\n [handle] =&gt; elementor-frontend\n [src] =&gt; http://example.com/wp-content/plugins/elementor/assets/js/frontend.js\n [deps] =&gt; Array\n (\n [0] =&gt; elementor-waypoints\n [1] =&gt; jquery-swiper\n )\n\n [ver] =&gt; 1.9.7\n [args] =&gt; \n [extra] =&gt; Array\n (\n [group] =&gt; 1\n )\n\n)\n...\n</code></pre>\n" }, { "answer_id": 382165, "author": "Nic Bug", "author_id": 144969, "author_profile": "https://wordpress.stackexchange.com/users/144969", "pm_score": 0, "selected": false, "text": "<p>why not simple use the elementor hooks to unset an asset? like this:</p>\n<pre><code>function remove_elementor_swiper() {\n wp_dequeue_script( 'swiper' );\n wp_deregister_script( 'swiper' );\n \n}\nadd_action( 'elementor/frontend/after_register_scripts', 'remove_elementor_swiper' );\n</code></pre>\n" } ]
2018/03/06
[ "https://wordpress.stackexchange.com/questions/295912", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22728/" ]
Please note that, I'm not telling about conditionally enqueue/dequeue scripts, I'm referring to conditionally dequeue certain dependencies from an existing enqueued scripts in front end. And please note the question is not plugin-specific. I want to be enlightened about the general rules. I used Elementor (page builder) for front end. But it's not used in all my pages. So the default lightbox feature enabled in Elementor doesn't work in those pages. That's why I added [my own lightbox](https://github.com/fancyapps/fancybox/) throughout the site, using a regex `$pattern ="/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";` hooked to the `the_content` filter. Thing's working fine, but- Where there the Elementor gallery or lightbox is triggered, both the scripts are messing up. Two lightbox are being called, sometimes the gallery lightbox are conflicting and not working etc. Solution 1: ----------- I know I can conditionally filter `the_content` with the regex like: ``` if( ! is_singular('cpt') ) { return $content = preg_replace($pattern, $replacement, $content); } ``` But I actually want to keep this feature everywhere. Just want to remove the elementor lightbox where I want 'em to. So, I's trying the solution#2. Solution 2: ----------- What Elementor did, is something, *like*: ``` wp_enqueue_script('elementor-frontend', 'link/to/frontend.js', array('elementor-dialog', 'elementor-waypoints', 'jquery-swiper'), '1.9.7', true); ``` Now I want not to load the lightbox feature from Elementor, so I tried to dequeue the `'elementor-dialog'`: ``` if( is_singular('cpt') ) { wp_dequeue_script( 'elementor-dialog' ); } ``` But it's not working, as the dependencies are set in `'elementor-frontend'`. So I tried deregistering dialog: ``` if( is_singular('cpt') ) { wp_dequeue_script( 'elementor-dialog' ); wp_deregister_script( 'elementor-dialog' ); } ``` It's devastating, because it dequeued the `frontend.js`. How can I change the dependencies of `frontend.js` (handle: `'elementor-frontend'`) on the fly, so that I can change the dependencies to `array('elementor-waypoints', 'jquery-swiper')`?
Solution 1: ----------- Here we will dequeue and deregister `elementor-dialog` *and* `elementor-frontend`, then we will re-register `elementor-frontend` without the `elementor-dialog` dependency: ``` // This needs to fire after priority 5 which is where Elementor // handles enqueueing scripts. We're ok since the default is 10. add_action( 'wp_enqueue_scripts', 'wpse_elementor_frontend_scripts' ); function wpse_elementor_frontend_scripts() { // Optionally add guard clauses such as checking if( ! is_singular('cpt') )... // Bail if Elementor is not available. if ( ! defined( 'ELEMENTOR_VERSION' ) ) { return; } // Dequeue and deregister elementor-dialog wp_dequeue_script( 'elementor-dialog' ); wp_deregister_script( 'elementor-dialog' ); // Dequeue and deregister elementor-frontend wp_dequeue_script( 'elementor-frontend' ); wp_deregister_script( 'elementor-frontend' ); // Re-register elementor-frontend without the elementor-dialog dependency. $suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min'; wp_register_script( 'elementor-frontend', ELEMENTOR_ASSETS_URL . 'js/frontend' . $suffix . '.js', [ //'elementor-dialog', // <-- We removed this 'elementor-waypoints', 'jquery-swiper', ], ELEMENTOR_VERSION, true ); // debugging... //$scripts = wp_scripts(); //exit ( print_r( $scripts ) ); } ``` Solution 2: ----------- In this solution, we will use `wp_scripts()` to modify the `$wp_scripts` global and then safely deregister `elementor-dialog`. We will remove the `elementor-dialog` dependency from the `elementor-frontend` handle, then dequeue the `elementor-dialog` script which is enqueued separately by the `Elementor\Frontend` class. ``` /** * The Elementor\Frontend class runs its register_scripts() method on * wp_enqueue_scripts at priority 5, so we want to hook in after this has taken place. */ add_action( 'wp_enqueue_scripts', 'wpse_elementor_frontend_scripts_modifier', 6 ); function wpse_elementor_frontend_scripts_modifier() { // Customize guard clauses to bail if we don't want to run this code. /*if ( ! is_singular( 'cpt' ) ) { return; }*/ // Get all scripts. $scripts = wp_scripts(); // Bail if something went wrong. if ( ! ( $scripts instanceof WP_Scripts ) ) { return; } // Array of handles to remove. $handles_to_remove = [ 'elementor-dialog', ]; // Flag indicating if we have removed the handles. $handles_updated = false; // Remove desired handles from the elementor-frontend script. foreach ( $scripts->registered as $dependency_object_id => $dependency_object ) { if ( 'elementor-frontend' === $dependency_object_id ) { // Bail if something went wrong. if ( ! ( $dependency_object instanceof _WP_Dependency ) ) { return; } // Bail if there are no dependencies for some reason. if ( empty( $dependency_object->deps ) ) { return; } // Do the handle removal. foreach ( $dependency_object->deps as $dep_key => $handle ) { if ( in_array( $handle, $handles_to_remove ) ) { unset( $dependency_object->deps[ $dep_key ] ); $dependency_object->deps = array_values( $dependency_object->deps ); // "reindex" array $handles_updated = true; } } } } // If we have updated the handles, dequeue the relevant dependencies which // were enqueued separately Elementor\Frontend. if ( $handles_updated ) { wp_dequeue_script( 'elementor-dialog' ); wp_deregister_script( 'elementor-dialog' ); } } ``` By modifying `elementor-frontend` before dequeueing `elementor-dialog`, we will not unintentionally dequeue `elementor-frontend` when we dequeue `elementor-dialog`. When testing this code, I inspected the `$wp_scripts` global (via `wp_scripts()`) to ensure that the desired results took effect. E.g. ``` $scripts = wp_scripts(); print_r( $scripts ); ``` **Relevant part of `$scripts` before modification:** ``` ... [elementor-dialog] => _WP_Dependency Object ( [handle] => elementor-dialog [src] => http://example.com/wp-content/plugins/elementor/assets/lib/dialog/dialog.js [deps] => Array ( [0] => jquery-ui-position ) [ver] => 4.1.0 [args] => [extra] => Array ( [group] => 1 ) ) [elementor-frontend] => _WP_Dependency Object ( [handle] => elementor-frontend [src] => http://example.com/wp-content/plugins/elementor/assets/js/frontend.js [deps] => Array ( [0] => elementor-dialog [1] => elementor-waypoints [2] => jquery-swiper ) [ver] => 1.9.7 [args] => [extra] => Array ( [group] => 1 ) ) ... ``` **Relevant part of `$scripts` after modification:** (Note that the `elementor-dialog` node has now been removed.) ``` ... [elementor-frontend] => _WP_Dependency Object ( [handle] => elementor-frontend [src] => http://example.com/wp-content/plugins/elementor/assets/js/frontend.js [deps] => Array ( [0] => elementor-waypoints [1] => jquery-swiper ) [ver] => 1.9.7 [args] => [extra] => Array ( [group] => 1 ) ) ... ```
295,919
<p>I need to add the same CSS class to <code>&lt;body&gt;</code> element of all translatons of a page, but the CSS class added with <code>body_class()</code> is different for each translation because it is taken from the translated title of the page.</p> <p>For example, for <em>about us</em> page I get this markup:</p> <pre><code>&lt;body class="about-us"&gt; // English &lt;body class="sobre-nosotros"&gt; // Spanish </code></pre> <p>I want to get the same class for both languages:</p> <pre><code>&lt;body class="about-us"&gt; // English &lt;body class="about-us"&gt; // Spanish </code></pre> <p>Is there a way to add the same CSS class for all translations of the same page?</p> <p>Thank you.</p>
[ { "answer_id": 295927, "author": "ZecKa", "author_id": 82323, "author_profile": "https://wordpress.stackexchange.com/users/82323", "pm_score": 3, "selected": true, "text": "<p>It's not a good practice to use post name to style your page. Maybe you can use template page.</p>\n\n<p>But if you still want to do it, you can do something like this:</p>\n\n<pre><code>function add_default_language_slug_class( $classes ) {\n global $post;\n if ( isset( $post ) ) {\n $default_language = wpml_get_default_language(); // will return languague code of your default language for example 'en'\n // get the post ID in default language\n $default_post_id = icl_object_id($post-&gt;ID, 'post', FALSE,$default_language);\n // get the post object\n $default_post_obj = get_post($default_post_id);\n // get the name\n $default_post_name = $default_post_obj-&gt;post_name;\n // add default language post name to body class\n $classes[] = $default_post_name;\n }\n return $classes;\n}\nadd_filter( 'body_class', 'add_default_language_slug_class' );\n</code></pre>\n" }, { "answer_id": 295929, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 0, "selected": false, "text": "<p>Yes, you can do that by <code>body_class</code> filter. You can add class to body like this-</p>\n\n<pre><code>// Add specific CSS class by filter\nadd_filter( 'body_class', 'the_dramatist_body_classes' );\nfunction the_dramatist_body_classes( $classes ) {\n return $classes[] = 'body-of-' . ICL_LANGUAGE_CODE;\n}\n</code></pre>\n\n<p>And then you can write CSS like below-</p>\n\n<pre><code>body[class^=\"body-of-\"] {\n color: red;\n}\n</code></pre>\n\n<p>So what is actually happening above ? First we are adding <em>body-of-en</em> for <strong>English</strong> and <em>body-of-es</em> for <strong>Spanish</strong> site and then we are adding CSS style by selecting them with <code>body[class^=\"body-of-\"]</code> means by the first part of the class we added to the body. This way we can easily add separate class to different language site's body as well as use them for applying same style also.</p>\n\n<p>Hope that helps.</p>\n" } ]
2018/03/06
[ "https://wordpress.stackexchange.com/questions/295919", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77722/" ]
I need to add the same CSS class to `<body>` element of all translatons of a page, but the CSS class added with `body_class()` is different for each translation because it is taken from the translated title of the page. For example, for *about us* page I get this markup: ``` <body class="about-us"> // English <body class="sobre-nosotros"> // Spanish ``` I want to get the same class for both languages: ``` <body class="about-us"> // English <body class="about-us"> // Spanish ``` Is there a way to add the same CSS class for all translations of the same page? Thank you.
It's not a good practice to use post name to style your page. Maybe you can use template page. But if you still want to do it, you can do something like this: ``` function add_default_language_slug_class( $classes ) { global $post; if ( isset( $post ) ) { $default_language = wpml_get_default_language(); // will return languague code of your default language for example 'en' // get the post ID in default language $default_post_id = icl_object_id($post->ID, 'post', FALSE,$default_language); // get the post object $default_post_obj = get_post($default_post_id); // get the name $default_post_name = $default_post_obj->post_name; // add default language post name to body class $classes[] = $default_post_name; } return $classes; } add_filter( 'body_class', 'add_default_language_slug_class' ); ```
295,936
<p>i a have a woocommerce file "checkout-form.php". I want remove the following actions via functions.php</p> <pre><code>&lt;?php do_action( 'woocommerce_checkout_after_order_review' ); ?&gt; &lt;/form&gt; &lt;?php do_action( 'woocommerce_after_checkout_form', $checkout ); ?&gt; </code></pre> <p>I used the following code in the functions.php but nothing happens:</p> <pre><code>remove_action( 'woocommerce_checkout_after_order_review', 10); remove_action( 'woocommerce_after_checkout_form', $checkout, 20); </code></pre> <p>i cant find the error. When i delete the "actions" manually in the woocommerce file it works. with the "remove_action function in the functions.php i have no effect. </p> <p>Where is my error?</p>
[ { "answer_id": 295939, "author": "Ravi Patel", "author_id": 35477, "author_profile": "https://wordpress.stackexchange.com/users/35477", "pm_score": 0, "selected": false, "text": "<p>You have remove specific action using remove_action.</p>\n\n<p>So you can find all actions related to this and remove using functions.</p>\n\n<pre><code> function action_woocommerce_checkout_after_order_review( ) { \n // make action magic happen here... \n }; \n\n // add the action \n add_action( 'woocommerce_checkout_after_order_review', 'action_woocommerce_checkout_after_order_review', 10, 0 ); \n\n remove_action( 'woocommerce_checkout_after_order_review','action_woocommerce_checkout_after_order_review',10, 0 );\n\n function action_woocommerce_after_checkout_form( $wccm_after_checkout ) { \n // make action magic happen here... \n }; \n\n // add the action \n add_action( 'woocommerce_after_checkout_form', 'action_woocommerce_after_checkout_form', 10, 1 )\n\n remove_action( 'woocommerce_after_checkout_form', 'action_woocommerce_after_checkout_form', 10, 1 ); \n</code></pre>\n\n<p>IF need to show error log enable config.php on wp_debug with true.</p>\n\n<p>Now you want's remove do_action() so please override \"form-checkout.php\" file copy from plugin and add in your theme and create directory with this path </p>\n\n<blockquote>\n <p>\"woocommerce/checkout/form-checkout.php\"</p>\n</blockquote>\n" }, { "answer_id": 295946, "author": "obiPlabon", "author_id": 135737, "author_profile": "https://wordpress.stackexchange.com/users/135737", "pm_score": 1, "selected": false, "text": "<p>First of all, you have to understand how hooks or more specifically how action hooks work. We use <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\"><code>add_action( $name, $callback )</code></a> to register an action hook which takes a name and a callback function as a required parameter. And we use <a href=\"https://developer.wordpress.org/reference/functions/do_action/\" rel=\"nofollow noreferrer\"><code>do_action( $name )</code></a> to run those registered action hooks which has been registered using <code>add_action()</code>.</p>\n\n<p>Now, if we want to remove an action hook or more precisely a registered action hook then we will use <a href=\"https://developer.wordpress.org/reference/functions/remove_action/\" rel=\"nofollow noreferrer\"><code>remove_action( $name, $callback )</code></a> which takes the same parameter as <code>add_action()</code>. So, to remove an action you have to know not only the action name but also the callback function name. You should know that there can be multiple actions with the same action name.</p>\n\n<p><strong>Example</strong></p>\n\n<pre><code>do_action( 'wp_enqueue_scripts' ); // Executing action hooks\n\nfunction op_enqueue_scripts() {\n // ...\n}\n\nfunction op_enqueue_google_fonts() {\n // ...\n}\n\nadd_action( 'wp_enqueue_scripts', 'op_enqueue_scripts' ); // Register an action hook\nadd_action( 'wp_enqueue_scripts', 'op_enqueue_google_fonts' ); // Register another action hook\n</code></pre>\n\n<p><strong>Remove action hook</strong></p>\n\n<pre><code>remove_action( 'wp_enqueue_scripts', 'op_enqueue_google_fonts' ); // Remove an action hook\n</code></pre>\n" }, { "answer_id": 295950, "author": "Dixita", "author_id": 114646, "author_profile": "https://wordpress.stackexchange.com/users/114646", "pm_score": -1, "selected": false, "text": "<p>You have to override return blank function for specific action.</p>\n\n<p>Try this:</p>\n\n<pre><code>function remove_woocommerce_checkout_after_order_review( ) { \n // \n}; \n\nadd_action( 'woocommerce_checkout_after_order_review', 'remove_woocommerce_checkout_after_order_review', 10, 0 ); \n\n\nfunction remove_woocommerce_after_checkout_form( ) { \n // \n}; \n\nadd_action( 'woocommerce_after_checkout_form', 'remove_woocommerce_after_checkout_form', 10, 1 )\n</code></pre>\n" } ]
2018/03/06
[ "https://wordpress.stackexchange.com/questions/295936", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82174/" ]
i a have a woocommerce file "checkout-form.php". I want remove the following actions via functions.php ``` <?php do_action( 'woocommerce_checkout_after_order_review' ); ?> </form> <?php do_action( 'woocommerce_after_checkout_form', $checkout ); ?> ``` I used the following code in the functions.php but nothing happens: ``` remove_action( 'woocommerce_checkout_after_order_review', 10); remove_action( 'woocommerce_after_checkout_form', $checkout, 20); ``` i cant find the error. When i delete the "actions" manually in the woocommerce file it works. with the "remove\_action function in the functions.php i have no effect. Where is my error?
First of all, you have to understand how hooks or more specifically how action hooks work. We use [`add_action( $name, $callback )`](https://developer.wordpress.org/reference/functions/add_action/) to register an action hook which takes a name and a callback function as a required parameter. And we use [`do_action( $name )`](https://developer.wordpress.org/reference/functions/do_action/) to run those registered action hooks which has been registered using `add_action()`. Now, if we want to remove an action hook or more precisely a registered action hook then we will use [`remove_action( $name, $callback )`](https://developer.wordpress.org/reference/functions/remove_action/) which takes the same parameter as `add_action()`. So, to remove an action you have to know not only the action name but also the callback function name. You should know that there can be multiple actions with the same action name. **Example** ``` do_action( 'wp_enqueue_scripts' ); // Executing action hooks function op_enqueue_scripts() { // ... } function op_enqueue_google_fonts() { // ... } add_action( 'wp_enqueue_scripts', 'op_enqueue_scripts' ); // Register an action hook add_action( 'wp_enqueue_scripts', 'op_enqueue_google_fonts' ); // Register another action hook ``` **Remove action hook** ``` remove_action( 'wp_enqueue_scripts', 'op_enqueue_google_fonts' ); // Remove an action hook ```
295,940
<p>I am trying to modify a theme by its child theme. The author already create a child theme.</p> <p>I add many thing in the stylesheet, but it's not working. When I check in Developer mode. I see the link rel for stylesheet is <strong><em><a href="https://.../style.css?ver=494" rel="nofollow noreferrer">https://.../style.css?ver=494</a></em></strong></p> <p>and <strong>style.css?ver=494</strong> is empty</p> <p>I think the functions.php that author made has some problem so I attach the functions.php (child theme) here:</p> <pre><code>&lt;?php // Exit if accessed directly if ( !defined( 'ABSPATH' ) ) exit; // BEGIN ENQUEUE PARENT ACTION // AUTO GENERATED - Do not modify or remove comment markers above or below: if ( !function_exists( 'chld_thm_cfg_parent_css' ) ): function chld_thm_cfg_parent_css() { wp_enqueue_style( 'chld_thm_cfg_parent', trailingslashit( get_template_directory_uri() ) . 'style.css', array( 'bootstrap','animate-css','carousel-css','fancybox-css','webkit-css','font-awesome-css' ) ); } endif; add_action( 'wp_enqueue_scripts', 'chld_thm_cfg_parent_css', 10 ); // END ENQUEUE PARENT ACTION </code></pre> <p>I also attached the style.css (child theme) hereunder:</p> <pre><code>/* Theme Name: Fitnesspoint Child Theme URI: http://fitnesspointwptheme.staging7.in/fitnesspoint/ Template: fitnesspoint Author: multidots Author URI: https://store.multidots.com/themes/wordpress-themes/ Description: Fitness Point is an Wordpress template for health sports club, personal gym trainer, gym, gym shop and fitness websites. It is a highly suitable template for fitness companies as well as gyms or sports clubs. It has the purpose oriented design, responsive layout and special features like gym shop, services, courses, fitness plans and other pages. Tags: custom-header,custom-background,threaded-comments,sticky-post,translation-ready,microformats,editor-style,custom-menu Version: 1.8.3 */ #primary-menu i.fa.fa-home { font-size: 20px; } section#huan-luyen { background-repeat: no-repeat; background-position: right; background-size: auto 100%; } .back-to-top { height: 130px; right: 25px; } </code></pre> <p>Please help me!!!</p> <p>P/S: I would like to have your ideas about changing the font in mysite. The theme fitnesspoint is using Latin-base Google Font. But my site is in Vietnamese. How to change it? Tnx</p>
[ { "answer_id": 295939, "author": "Ravi Patel", "author_id": 35477, "author_profile": "https://wordpress.stackexchange.com/users/35477", "pm_score": 0, "selected": false, "text": "<p>You have remove specific action using remove_action.</p>\n\n<p>So you can find all actions related to this and remove using functions.</p>\n\n<pre><code> function action_woocommerce_checkout_after_order_review( ) { \n // make action magic happen here... \n }; \n\n // add the action \n add_action( 'woocommerce_checkout_after_order_review', 'action_woocommerce_checkout_after_order_review', 10, 0 ); \n\n remove_action( 'woocommerce_checkout_after_order_review','action_woocommerce_checkout_after_order_review',10, 0 );\n\n function action_woocommerce_after_checkout_form( $wccm_after_checkout ) { \n // make action magic happen here... \n }; \n\n // add the action \n add_action( 'woocommerce_after_checkout_form', 'action_woocommerce_after_checkout_form', 10, 1 )\n\n remove_action( 'woocommerce_after_checkout_form', 'action_woocommerce_after_checkout_form', 10, 1 ); \n</code></pre>\n\n<p>IF need to show error log enable config.php on wp_debug with true.</p>\n\n<p>Now you want's remove do_action() so please override \"form-checkout.php\" file copy from plugin and add in your theme and create directory with this path </p>\n\n<blockquote>\n <p>\"woocommerce/checkout/form-checkout.php\"</p>\n</blockquote>\n" }, { "answer_id": 295946, "author": "obiPlabon", "author_id": 135737, "author_profile": "https://wordpress.stackexchange.com/users/135737", "pm_score": 1, "selected": false, "text": "<p>First of all, you have to understand how hooks or more specifically how action hooks work. We use <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\"><code>add_action( $name, $callback )</code></a> to register an action hook which takes a name and a callback function as a required parameter. And we use <a href=\"https://developer.wordpress.org/reference/functions/do_action/\" rel=\"nofollow noreferrer\"><code>do_action( $name )</code></a> to run those registered action hooks which has been registered using <code>add_action()</code>.</p>\n\n<p>Now, if we want to remove an action hook or more precisely a registered action hook then we will use <a href=\"https://developer.wordpress.org/reference/functions/remove_action/\" rel=\"nofollow noreferrer\"><code>remove_action( $name, $callback )</code></a> which takes the same parameter as <code>add_action()</code>. So, to remove an action you have to know not only the action name but also the callback function name. You should know that there can be multiple actions with the same action name.</p>\n\n<p><strong>Example</strong></p>\n\n<pre><code>do_action( 'wp_enqueue_scripts' ); // Executing action hooks\n\nfunction op_enqueue_scripts() {\n // ...\n}\n\nfunction op_enqueue_google_fonts() {\n // ...\n}\n\nadd_action( 'wp_enqueue_scripts', 'op_enqueue_scripts' ); // Register an action hook\nadd_action( 'wp_enqueue_scripts', 'op_enqueue_google_fonts' ); // Register another action hook\n</code></pre>\n\n<p><strong>Remove action hook</strong></p>\n\n<pre><code>remove_action( 'wp_enqueue_scripts', 'op_enqueue_google_fonts' ); // Remove an action hook\n</code></pre>\n" }, { "answer_id": 295950, "author": "Dixita", "author_id": 114646, "author_profile": "https://wordpress.stackexchange.com/users/114646", "pm_score": -1, "selected": false, "text": "<p>You have to override return blank function for specific action.</p>\n\n<p>Try this:</p>\n\n<pre><code>function remove_woocommerce_checkout_after_order_review( ) { \n // \n}; \n\nadd_action( 'woocommerce_checkout_after_order_review', 'remove_woocommerce_checkout_after_order_review', 10, 0 ); \n\n\nfunction remove_woocommerce_after_checkout_form( ) { \n // \n}; \n\nadd_action( 'woocommerce_after_checkout_form', 'remove_woocommerce_after_checkout_form', 10, 1 )\n</code></pre>\n" } ]
2018/03/06
[ "https://wordpress.stackexchange.com/questions/295940", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138087/" ]
I am trying to modify a theme by its child theme. The author already create a child theme. I add many thing in the stylesheet, but it's not working. When I check in Developer mode. I see the link rel for stylesheet is ***<https://.../style.css?ver=494>*** and **style.css?ver=494** is empty I think the functions.php that author made has some problem so I attach the functions.php (child theme) here: ``` <?php // Exit if accessed directly if ( !defined( 'ABSPATH' ) ) exit; // BEGIN ENQUEUE PARENT ACTION // AUTO GENERATED - Do not modify or remove comment markers above or below: if ( !function_exists( 'chld_thm_cfg_parent_css' ) ): function chld_thm_cfg_parent_css() { wp_enqueue_style( 'chld_thm_cfg_parent', trailingslashit( get_template_directory_uri() ) . 'style.css', array( 'bootstrap','animate-css','carousel-css','fancybox-css','webkit-css','font-awesome-css' ) ); } endif; add_action( 'wp_enqueue_scripts', 'chld_thm_cfg_parent_css', 10 ); // END ENQUEUE PARENT ACTION ``` I also attached the style.css (child theme) hereunder: ``` /* Theme Name: Fitnesspoint Child Theme URI: http://fitnesspointwptheme.staging7.in/fitnesspoint/ Template: fitnesspoint Author: multidots Author URI: https://store.multidots.com/themes/wordpress-themes/ Description: Fitness Point is an Wordpress template for health sports club, personal gym trainer, gym, gym shop and fitness websites. It is a highly suitable template for fitness companies as well as gyms or sports clubs. It has the purpose oriented design, responsive layout and special features like gym shop, services, courses, fitness plans and other pages. Tags: custom-header,custom-background,threaded-comments,sticky-post,translation-ready,microformats,editor-style,custom-menu Version: 1.8.3 */ #primary-menu i.fa.fa-home { font-size: 20px; } section#huan-luyen { background-repeat: no-repeat; background-position: right; background-size: auto 100%; } .back-to-top { height: 130px; right: 25px; } ``` Please help me!!! P/S: I would like to have your ideas about changing the font in mysite. The theme fitnesspoint is using Latin-base Google Font. But my site is in Vietnamese. How to change it? Tnx
First of all, you have to understand how hooks or more specifically how action hooks work. We use [`add_action( $name, $callback )`](https://developer.wordpress.org/reference/functions/add_action/) to register an action hook which takes a name and a callback function as a required parameter. And we use [`do_action( $name )`](https://developer.wordpress.org/reference/functions/do_action/) to run those registered action hooks which has been registered using `add_action()`. Now, if we want to remove an action hook or more precisely a registered action hook then we will use [`remove_action( $name, $callback )`](https://developer.wordpress.org/reference/functions/remove_action/) which takes the same parameter as `add_action()`. So, to remove an action you have to know not only the action name but also the callback function name. You should know that there can be multiple actions with the same action name. **Example** ``` do_action( 'wp_enqueue_scripts' ); // Executing action hooks function op_enqueue_scripts() { // ... } function op_enqueue_google_fonts() { // ... } add_action( 'wp_enqueue_scripts', 'op_enqueue_scripts' ); // Register an action hook add_action( 'wp_enqueue_scripts', 'op_enqueue_google_fonts' ); // Register another action hook ``` **Remove action hook** ``` remove_action( 'wp_enqueue_scripts', 'op_enqueue_google_fonts' ); // Remove an action hook ```
295,959
<p>I have a plugin which I downloaded and removed alot off stuff I don't need from. I also renamed it for simplicity, but right now it is linked to some other plugin, close to the name I gave it. If I go to Plugins under WP-Admin I can press View details. And it brings me information about a plugin with the name I gave it.</p> <p>How do I unmatch this? So that it won't update if that plugins receives an update?</p> <p>Thank you!</p>
[ { "answer_id": 295939, "author": "Ravi Patel", "author_id": 35477, "author_profile": "https://wordpress.stackexchange.com/users/35477", "pm_score": 0, "selected": false, "text": "<p>You have remove specific action using remove_action.</p>\n\n<p>So you can find all actions related to this and remove using functions.</p>\n\n<pre><code> function action_woocommerce_checkout_after_order_review( ) { \n // make action magic happen here... \n }; \n\n // add the action \n add_action( 'woocommerce_checkout_after_order_review', 'action_woocommerce_checkout_after_order_review', 10, 0 ); \n\n remove_action( 'woocommerce_checkout_after_order_review','action_woocommerce_checkout_after_order_review',10, 0 );\n\n function action_woocommerce_after_checkout_form( $wccm_after_checkout ) { \n // make action magic happen here... \n }; \n\n // add the action \n add_action( 'woocommerce_after_checkout_form', 'action_woocommerce_after_checkout_form', 10, 1 )\n\n remove_action( 'woocommerce_after_checkout_form', 'action_woocommerce_after_checkout_form', 10, 1 ); \n</code></pre>\n\n<p>IF need to show error log enable config.php on wp_debug with true.</p>\n\n<p>Now you want's remove do_action() so please override \"form-checkout.php\" file copy from plugin and add in your theme and create directory with this path </p>\n\n<blockquote>\n <p>\"woocommerce/checkout/form-checkout.php\"</p>\n</blockquote>\n" }, { "answer_id": 295946, "author": "obiPlabon", "author_id": 135737, "author_profile": "https://wordpress.stackexchange.com/users/135737", "pm_score": 1, "selected": false, "text": "<p>First of all, you have to understand how hooks or more specifically how action hooks work. We use <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\"><code>add_action( $name, $callback )</code></a> to register an action hook which takes a name and a callback function as a required parameter. And we use <a href=\"https://developer.wordpress.org/reference/functions/do_action/\" rel=\"nofollow noreferrer\"><code>do_action( $name )</code></a> to run those registered action hooks which has been registered using <code>add_action()</code>.</p>\n\n<p>Now, if we want to remove an action hook or more precisely a registered action hook then we will use <a href=\"https://developer.wordpress.org/reference/functions/remove_action/\" rel=\"nofollow noreferrer\"><code>remove_action( $name, $callback )</code></a> which takes the same parameter as <code>add_action()</code>. So, to remove an action you have to know not only the action name but also the callback function name. You should know that there can be multiple actions with the same action name.</p>\n\n<p><strong>Example</strong></p>\n\n<pre><code>do_action( 'wp_enqueue_scripts' ); // Executing action hooks\n\nfunction op_enqueue_scripts() {\n // ...\n}\n\nfunction op_enqueue_google_fonts() {\n // ...\n}\n\nadd_action( 'wp_enqueue_scripts', 'op_enqueue_scripts' ); // Register an action hook\nadd_action( 'wp_enqueue_scripts', 'op_enqueue_google_fonts' ); // Register another action hook\n</code></pre>\n\n<p><strong>Remove action hook</strong></p>\n\n<pre><code>remove_action( 'wp_enqueue_scripts', 'op_enqueue_google_fonts' ); // Remove an action hook\n</code></pre>\n" }, { "answer_id": 295950, "author": "Dixita", "author_id": 114646, "author_profile": "https://wordpress.stackexchange.com/users/114646", "pm_score": -1, "selected": false, "text": "<p>You have to override return blank function for specific action.</p>\n\n<p>Try this:</p>\n\n<pre><code>function remove_woocommerce_checkout_after_order_review( ) { \n // \n}; \n\nadd_action( 'woocommerce_checkout_after_order_review', 'remove_woocommerce_checkout_after_order_review', 10, 0 ); \n\n\nfunction remove_woocommerce_after_checkout_form( ) { \n // \n}; \n\nadd_action( 'woocommerce_after_checkout_form', 'remove_woocommerce_after_checkout_form', 10, 1 )\n</code></pre>\n" } ]
2018/03/06
[ "https://wordpress.stackexchange.com/questions/295959", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138051/" ]
I have a plugin which I downloaded and removed alot off stuff I don't need from. I also renamed it for simplicity, but right now it is linked to some other plugin, close to the name I gave it. If I go to Plugins under WP-Admin I can press View details. And it brings me information about a plugin with the name I gave it. How do I unmatch this? So that it won't update if that plugins receives an update? Thank you!
First of all, you have to understand how hooks or more specifically how action hooks work. We use [`add_action( $name, $callback )`](https://developer.wordpress.org/reference/functions/add_action/) to register an action hook which takes a name and a callback function as a required parameter. And we use [`do_action( $name )`](https://developer.wordpress.org/reference/functions/do_action/) to run those registered action hooks which has been registered using `add_action()`. Now, if we want to remove an action hook or more precisely a registered action hook then we will use [`remove_action( $name, $callback )`](https://developer.wordpress.org/reference/functions/remove_action/) which takes the same parameter as `add_action()`. So, to remove an action you have to know not only the action name but also the callback function name. You should know that there can be multiple actions with the same action name. **Example** ``` do_action( 'wp_enqueue_scripts' ); // Executing action hooks function op_enqueue_scripts() { // ... } function op_enqueue_google_fonts() { // ... } add_action( 'wp_enqueue_scripts', 'op_enqueue_scripts' ); // Register an action hook add_action( 'wp_enqueue_scripts', 'op_enqueue_google_fonts' ); // Register another action hook ``` **Remove action hook** ``` remove_action( 'wp_enqueue_scripts', 'op_enqueue_google_fonts' ); // Remove an action hook ```
295,992
<p>I know that you can install plugin code as part of a theme, but I would like to do it the other way round. I'm developing a plugin that changes many aspects of WordPress and most will not be visible without my theme providing support for it. In other words it makes very little sense to run the plugin without the theme. I understand that it's not encouraged/allowed to do this in plugins hosted on wordpress.org, but my plugin is not distributed there and requires an administrator to upload a zip (which I take to mean they will have read the readme that explains the side effects).</p> <p>It seems from <a href="https://wordpress.stackexchange.com/questions/13181/fully-automated-theme-install-and-activation-via-a-plugin">this question</a> that it's possible to use the plugin's activation function to copy the theme files to the necessary place and then activate it using <code>switch_theme</code>, but there are enough aspects of this method where something can go wrong (e.g. permission issues when copying the theme files) that I feel this is something better handled by WordPress core.</p> <p>Ideally, I hope there is a way that I can provide the theme files as part of my plugin, so that I only have to manage one project, and the user only has to update one plugin.</p>
[ { "answer_id": 295993, "author": "Sean", "author_id": 138112, "author_profile": "https://wordpress.stackexchange.com/users/138112", "pm_score": 0, "selected": false, "text": "<p>It looks like the function <a href=\"https://codex.wordpress.org/Function_Reference/register_theme_directory\" rel=\"nofollow noreferrer\"><code>register_theme_directory</code></a> can be used for this purpose.</p>\n" }, { "answer_id": 412320, "author": "samjco", "author_id": 29133, "author_profile": "https://wordpress.stackexchange.com/users/29133", "pm_score": 2, "selected": true, "text": "<p>Well instead of copying a theme over which would require file permissions, etc, you can add the themes files to the plugin folder and activate it from there:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function updateTheme($theme){\n update_option('template', $theme);\n update_option('stylesheet', $theme);\n update_option('current_theme', $theme);\n}\n\nadd_action( 'setup_theme', 'change_theme' );\n\nfunction change_theme() {\n\n if($enable_theme == true):\n\n /*** if the theme exists in your plugin file**/\n register_theme_directory( plugin_dir_path( __FILE__ ) . 'themes' );\n \n $theme = &quot;mythemename&quot;; // Other theme name to load\n\n else:\n\n $theme = &quot;default&quot;;\n\n endif;\n\n updateTheme($theme);\n}\n</code></pre>\n" } ]
2018/03/06
[ "https://wordpress.stackexchange.com/questions/295992", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138112/" ]
I know that you can install plugin code as part of a theme, but I would like to do it the other way round. I'm developing a plugin that changes many aspects of WordPress and most will not be visible without my theme providing support for it. In other words it makes very little sense to run the plugin without the theme. I understand that it's not encouraged/allowed to do this in plugins hosted on wordpress.org, but my plugin is not distributed there and requires an administrator to upload a zip (which I take to mean they will have read the readme that explains the side effects). It seems from [this question](https://wordpress.stackexchange.com/questions/13181/fully-automated-theme-install-and-activation-via-a-plugin) that it's possible to use the plugin's activation function to copy the theme files to the necessary place and then activate it using `switch_theme`, but there are enough aspects of this method where something can go wrong (e.g. permission issues when copying the theme files) that I feel this is something better handled by WordPress core. Ideally, I hope there is a way that I can provide the theme files as part of my plugin, so that I only have to manage one project, and the user only has to update one plugin.
Well instead of copying a theme over which would require file permissions, etc, you can add the themes files to the plugin folder and activate it from there: ```php function updateTheme($theme){ update_option('template', $theme); update_option('stylesheet', $theme); update_option('current_theme', $theme); } add_action( 'setup_theme', 'change_theme' ); function change_theme() { if($enable_theme == true): /*** if the theme exists in your plugin file**/ register_theme_directory( plugin_dir_path( __FILE__ ) . 'themes' ); $theme = "mythemename"; // Other theme name to load else: $theme = "default"; endif; updateTheme($theme); } ```
296,038
<p>Is there a WP-CLI command to disable comment windows for all existing posts (pages/blogposts)?</p> <p>I ask this since when I change a theme for a site I have, all pages in that site getting their comment windows again and I need to individually disable comments per each page.</p> <p>In this particular site I have up to 10 webpages but in any case I'd like to that with WP-CLI. Is it possible?</p> <p>If you don't know a way with WP-CLI please at least share another good way you know.</p>
[ { "answer_id": 296042, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>Here is an untested suggestion for wp-cli approach:</p>\n\n<p>We can list post IDs of published posts with <em>open</em> comment status with:</p>\n\n<pre><code>wp post list --post-status=publish --post_type=post comment_status=open --format=ids\n</code></pre>\n\n<p>and update a post to a <em>closed</em> comment status with:</p>\n\n<pre><code>wp post update 123 --comment_status=closed\n</code></pre>\n\n<p>where 123 is a post id.</p>\n\n<p>We can then combine those two into:</p>\n\n<pre><code>wp post list --post-status=publish --post_type=post comment_status=open --format=ids \\\n| xargs -d ' ' -I % wp post update % --comment_status=closed\n</code></pre>\n\n<p>or</p>\n\n<pre><code>for post_id in $(wp post list --post_status=publish \\\n --post_type=post --comment_status=open --format=ids); \\ \ndo wp post update $post_id --comment_status=closed; done;\n</code></pre>\n\n<p>Then there's the <code>ping_status</code> as well to consider.</p>\n\n<p>There are other ways than wp-cli but please remember to take <strong>backup</strong> before testing.</p>\n" }, { "answer_id": 300098, "author": "kierzniak", "author_id": 132363, "author_profile": "https://wordpress.stackexchange.com/users/132363", "pm_score": 1, "selected": false, "text": "<p>You can execute SQL query to change comment status of all posts using <code>wp db query</code> command.</p>\n\n<pre><code>wp db query \"UPDATE wp_posts SET comment_status = 'closed';\"\n</code></pre>\n" }, { "answer_id": 300190, "author": "Rakesh Roy", "author_id": 131649, "author_profile": "https://wordpress.stackexchange.com/users/131649", "pm_score": -1, "selected": false, "text": "<p>use this command to install the plugin </p>\n\n<pre><code>wp plugin install disable-comments\n</code></pre>\n\n<p>Use it from backend it has lots of Options</p>\n\n<p>Plugin Url: <a href=\"https://wordpress.org/plugins/disable-comments/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/disable-comments/</a></p>\n" } ]
2018/03/07
[ "https://wordpress.stackexchange.com/questions/296038", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136194/" ]
Is there a WP-CLI command to disable comment windows for all existing posts (pages/blogposts)? I ask this since when I change a theme for a site I have, all pages in that site getting their comment windows again and I need to individually disable comments per each page. In this particular site I have up to 10 webpages but in any case I'd like to that with WP-CLI. Is it possible? If you don't know a way with WP-CLI please at least share another good way you know.
Here is an untested suggestion for wp-cli approach: We can list post IDs of published posts with *open* comment status with: ``` wp post list --post-status=publish --post_type=post comment_status=open --format=ids ``` and update a post to a *closed* comment status with: ``` wp post update 123 --comment_status=closed ``` where 123 is a post id. We can then combine those two into: ``` wp post list --post-status=publish --post_type=post comment_status=open --format=ids \ | xargs -d ' ' -I % wp post update % --comment_status=closed ``` or ``` for post_id in $(wp post list --post_status=publish \ --post_type=post --comment_status=open --format=ids); \ do wp post update $post_id --comment_status=closed; done; ``` Then there's the `ping_status` as well to consider. There are other ways than wp-cli but please remember to take **backup** before testing.
296,056
<p>I have a Multisite setup, and I would like to hide all notices/notifications from the admin pages for everyone but me (the Super Admin). How would I manage to do this?</p> <p>Thank you!</p>
[ { "answer_id": 296060, "author": "Misha Rudrastyh", "author_id": 85985, "author_profile": "https://wordpress.stackexchange.com/users/85985", "pm_score": 4, "selected": true, "text": "<p>Try this code in your custom plugin which is better to activate for the network.</p>\n\n<pre><code>if ( !is_super_admin() ) {\n remove_all_actions('admin_notices');\n}\n</code></pre>\n" }, { "answer_id": 352401, "author": "Puya Fazlali", "author_id": 178222, "author_profile": "https://wordpress.stackexchange.com/users/178222", "pm_score": 1, "selected": false, "text": "<p>Try adding this function in the functions.php file of your theme.</p>\n\n<pre><code>function hide_update_noticee_to_all_but_admin_users()\n{\n if (!is_super_admin()) {\n remove_all_actions( 'admin_notices' );\n }\n}\nadd_action( 'admin_head', 'hide_update_noticee_to_all_but_admin_users', 1 );\n</code></pre>\n" }, { "answer_id": 385268, "author": "Mick McMurray", "author_id": 172959, "author_profile": "https://wordpress.stackexchange.com/users/172959", "pm_score": 3, "selected": false, "text": "<p>This is an old question, but I thought I'd share in case it helps someone else.</p>\n<p>Notices are added by the following actions (in this order):</p>\n<ul>\n<li><code>network_admin_notices</code> (for network admin--aka super admin. You don't want to remove these.)</li>\n<li><code>user_admin_notices</code> (for site admin)</li>\n<li><code>admin_notices</code> (for other users)</li>\n</ul>\n<p>The last action to be run before these is <code>in_admin_header</code> so that would be the best place to hook into to remove the notices.</p>\n<pre><code>function my_hide_notices_to_all_but_super_admin(){\n if (!is_super_admin()) {\n remove_all_actions( 'user_admin_notices' );\n remove_all_actions( 'admin_notices' );\n }\n}\nadd_action('in_admin_header', 'my_hide_notices_to_all_but_super_admin', 99);\n</code></pre>\n<p>I'm using a high priority of 99 to make it unlikely that notices get added in after this runs.</p>\n" } ]
2018/03/07
[ "https://wordpress.stackexchange.com/questions/296056", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138051/" ]
I have a Multisite setup, and I would like to hide all notices/notifications from the admin pages for everyone but me (the Super Admin). How would I manage to do this? Thank you!
Try this code in your custom plugin which is better to activate for the network. ``` if ( !is_super_admin() ) { remove_all_actions('admin_notices'); } ```
296,095
<p>i have two WordPress sites with SSO Configurations as described <a href="https://wordpress.stackexchange.com/questions/272122/single-sign-on-between-two-wordpress-website">here</a> but the plugin in the answer didn't work for me so i tried to write a code to add capabilities for second site users:</p> <pre> $wp_user_query = new WP_User_Query(array('role' => 'author')); $users = $wp_user_query->get_results(); if (!empty($users)) { foreach ($users as $user) { add_user_meta( $user->id, 'orewpst_capabilities', "a:1:{s:6:'author';b:1;}", true ); add_user_meta( $user->id, 'orewpst_user_level', '2', true ); } } </pre> <p>the problem is the output result for <code>&quot;a:1:{s:6:'author';b:1;}&quot;</code> is <code>s:23:&quot;a:1:{s:6:'author';b:1;}&quot;</code></p> <p>i don't know what &quot;s:23&quot; means and why it appears in database!</p> <p><strong>update</strong>: I want the string <code>&quot;a:1:{s:6:'author';b:1;}&quot;</code> to store in database with out any change! but somehow my code adds an &quot;s:23:&quot; before it.</p>
[ { "answer_id": 296108, "author": "Felipe Elia", "author_id": 122788, "author_profile": "https://wordpress.stackexchange.com/users/122788", "pm_score": 3, "selected": true, "text": "<p>Try passing the value without serializing it manually, because WordPress will do it for you anyway:</p>\n\n<pre><code>add_user_meta( $user-&gt;id, 'orewpst_capabilities', array( 'author' =&gt; 1 ), true );\n</code></pre>\n\n<p>or</p>\n\n<pre><code>update_user_meta( $user-&gt;id, 'orewpst_capabilities', array( 'author' =&gt; 1 ) ); // it will create the meta data for you if it doesn't exist already.\n</code></pre>\n\n<p>The <code>s:23</code> means that you stored a string with 23 chars.</p>\n\n<p>Hope it helps!</p>\n" }, { "answer_id": 296256, "author": "maheshwaghmare", "author_id": 52167, "author_profile": "https://wordpress.stackexchange.com/users/52167", "pm_score": 0, "selected": false, "text": "<p>That's right the <code>s:23</code> is serialized data. WordPress automatically store the data in serialized format.</p>\n\n<p>Also, To set the user capabilities use function <code>add_cap()</code> instead of updating the user meta. For more details check WordPress handbook <a href=\"https://developer.wordpress.org/plugins/users/roles-and-capabilities/\" rel=\"nofollow noreferrer\">user roles and capabilities</a>.</p>\n" } ]
2018/03/07
[ "https://wordpress.stackexchange.com/questions/296095", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123728/" ]
i have two WordPress sites with SSO Configurations as described [here](https://wordpress.stackexchange.com/questions/272122/single-sign-on-between-two-wordpress-website) but the plugin in the answer didn't work for me so i tried to write a code to add capabilities for second site users: ``` $wp_user_query = new WP_User_Query(array('role' => 'author')); $users = $wp_user_query->get_results(); if (!empty($users)) { foreach ($users as $user) { add_user_meta( $user->id, 'orewpst_capabilities', "a:1:{s:6:'author';b:1;}", true ); add_user_meta( $user->id, 'orewpst_user_level', '2', true ); } } ``` the problem is the output result for `"a:1:{s:6:'author';b:1;}"` is `s:23:"a:1:{s:6:'author';b:1;}"` i don't know what "s:23" means and why it appears in database! **update**: I want the string `"a:1:{s:6:'author';b:1;}"` to store in database with out any change! but somehow my code adds an "s:23:" before it.
Try passing the value without serializing it manually, because WordPress will do it for you anyway: ``` add_user_meta( $user->id, 'orewpst_capabilities', array( 'author' => 1 ), true ); ``` or ``` update_user_meta( $user->id, 'orewpst_capabilities', array( 'author' => 1 ) ); // it will create the meta data for you if it doesn't exist already. ``` The `s:23` means that you stored a string with 23 chars. Hope it helps!
296,115
<p>Lets say we have a do_action like this: </p> <pre><code>do_action('some_action'); </code></pre> <p>Doesn't this mean that there has to be a <code>some_action()</code> function somewhere in the wordpress like this for example:</p> <pre><code>function some_action(){ /* blah blah blah*/ } </code></pre> <p>My question comes from a <code>do_action()</code> at the storefront theme of woocommerce that has a line in header.php like this:</p> <pre><code>do_action( 'storefront_header' ); </code></pre> <p>But I haven't been able to find any <code>storefront_header()</code> function so I started wondering perhaps not all do_actions are coming with a function of their own. Is it possible?</p>
[ { "answer_id": 296118, "author": "Alex Sancho", "author_id": 2536, "author_profile": "https://wordpress.stackexchange.com/users/2536", "pm_score": 4, "selected": true, "text": "<p>The param used in <code>do_action</code> isn't a function is just a tag that represents the action called, the proper way to use an action is attaching functions with <code>add_action</code>.</p>\n\n<p>You can learn more from <a href=\"https://developer.wordpress.org/reference/functions/do_action/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/do_action/</a></p>\n" }, { "answer_id": 296119, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 2, "selected": false, "text": "<p>No.</p>\n<p>The <code>some_action</code> in <code>do_action( 'some_action' );</code> is an <em>action hook</em>, and allows you to cause actions to happen at a specific point in time during WordPress's lifecycle. If an action hook happens to share a name with a function, it's a coincidence (or often a convenience).</p>\n<p>From the glossary:</p>\n<blockquote>\n<p>… an Action is a PHP function that is executed at specific points throughout the WordPress Core.</p>\n<p>Developers can create a custom Action using the Action API to add or remove code from an existing Action by specifying any existing Hook. This process is called &quot;hooking&quot;.</p>\n</blockquote>\n<p>—<a href=\"https://codex.wordpress.org/Glossary#Action\" rel=\"nofollow noreferrer\">Glossary: Action</a></p>\n<p>Action hooks (and their cousins, filter hooks) are part of WordPress's rich <a href=\"https://codex.wordpress.org/Plugin_API\" rel=\"nofollow noreferrer\">Plugin API</a>.</p>\n" }, { "answer_id": 297043, "author": "Silicon Dales", "author_id": 39346, "author_profile": "https://wordpress.stackexchange.com/users/39346", "pm_score": 2, "selected": false, "text": "<p>You might want to have a look in <code>storefront/inc/storefront-template-hooks.php</code> see <a href=\"https://github.com/woocommerce/storefront/blob/1790927f8cab022bc96847fb0efc4f2f2ff6b2aa/inc/storefront-template-hooks.php\" rel=\"nofollow noreferrer\">https://github.com/woocommerce/storefront/blob/1790927f8cab022bc96847fb0efc4f2f2ff6b2aa/inc/storefront-template-hooks.php</a></p>\n\n<p>You can see the action in here, and the relevant functions (and order):</p>\n\n<pre><code>add_action( 'storefront_header', 'storefront_skip_links', 0 );\nadd_action( 'storefront_header', 'storefront_site_branding', 20 );\nadd_action( 'storefront_header', 'storefront_secondary_navigation', 30 );\nadd_action( 'storefront_header', 'storefront_primary_navigation_wrapper', 42 );\nadd_action( 'storefront_header', 'storefront_primary_navigation', 50 );\nadd_action( 'storefront_header', 'storefront_primary_navigation_wrapper_close', 68 );\n</code></pre>\n\n<p>With this first one, selected for example, the function here is <code>storefront_skip_links</code>, which is in <code>storefront/inc/storefront-template-functions.php</code> (line 279 at time of writing!) and looks like this:</p>\n\n<pre><code>if ( ! function_exists( 'storefront_skip_links' ) ) {\n /**\n * Skip links\n *\n * @since 1.4.1\n * @return void\n */\n function storefront_skip_links() {\n ?&gt;\n &lt;a class=\"skip-link screen-reader-text\" href=\"#site-navigation\"&gt;&lt;?php esc_attr_e( 'Skip to navigation', 'storefront' ); ?&gt;&lt;/a&gt;\n &lt;a class=\"skip-link screen-reader-text\" href=\"#content\"&gt;&lt;?php esc_attr_e( 'Skip to content', 'storefront' ); ?&gt;&lt;/a&gt;\n &lt;?php\n }\n}\n</code></pre>\n\n<p>Hope this helps you to understand how this works in practice!</p>\n" } ]
2018/03/07
[ "https://wordpress.stackexchange.com/questions/296115", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125637/" ]
Lets say we have a do\_action like this: ``` do_action('some_action'); ``` Doesn't this mean that there has to be a `some_action()` function somewhere in the wordpress like this for example: ``` function some_action(){ /* blah blah blah*/ } ``` My question comes from a `do_action()` at the storefront theme of woocommerce that has a line in header.php like this: ``` do_action( 'storefront_header' ); ``` But I haven't been able to find any `storefront_header()` function so I started wondering perhaps not all do\_actions are coming with a function of their own. Is it possible?
The param used in `do_action` isn't a function is just a tag that represents the action called, the proper way to use an action is attaching functions with `add_action`. You can learn more from <https://developer.wordpress.org/reference/functions/do_action/>
296,129
<p>I'm attempting to create a custom post type (doctors) that will load a custom page template (single-doctors.php). I've set up the custom post type through functions.php, and created a 'new doctor', selected the single-doctors template. But when I go to actually see the page, the template doesnt load and I'm presented with a "This page not found" page. I've been scouring the interwebs trying to find a solution to this. I find a lot of the same thing (flush permalinks, remove 'has_archive', etc.) but nothing has worked. </p> <p>As a workaround, I tried downloading a custom post plugin (Custom Post Type UI) and setting things up that way. This worked!! But i will be doing more custom post creation on future sites and want to be able to do this without the plugin. I tried taking the code generated by the plugin itself and replacing my code with theirs in my functions.php file. This did not work and I was back to the "Page not found" page. I'm pulling my hair out. Can anybody help me identify what puzzle piece I'm missing? Any help is greatly appreciated. My functions.php code and the plugin's code below...</p> <p>My code:</p> <pre><code>// Doctors add_action( 'init', 'doctors_init' ); function doctors_init() { $labels = array( 'name' =&gt; _x( 'Doctors', 'post type general name', 'AIN' ), 'singular_name' =&gt; _x( 'Doctor', 'post type singular name', 'AIN' ), 'menu_name' =&gt; _x( 'Doctors', 'admin menu', 'AIN' ), 'name_admin_bar' =&gt; _x( 'Doctor', 'add new on admin bar', 'AIN' ), 'add_new' =&gt; _x( 'Add New', 'Doctor', 'AIN' ), 'add_new_item' =&gt; __( 'Add New Doctor', 'AIN' ), 'new_item' =&gt; __( 'New Doctor', 'AIN' ), 'edit_item' =&gt; __( 'Edit Doctor', 'AIN' ), 'view_item' =&gt; __( 'View Doctor', 'AIN' ), 'all_items' =&gt; __( 'All Doctors', 'AIN' ), 'search_items' =&gt; __( 'Search Doctors', 'AIN' ), 'parent_item_colon' =&gt; __( 'Parent Doctors:', 'AIN' ), 'not_found' =&gt; __( 'No Doctors found.', 'AIN' ), 'not_found_in_trash' =&gt; __( 'No Doctors found in Trash.', 'AIN' ) ); $args = array( "label" =&gt; __( "doctors", "understrap-child" ), 'labels' =&gt; $labels, 'description' =&gt; __( 'Description.', 'AIN' ), 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'doctors', "with_front" =&gt; true ), 'capability_type' =&gt; 'post', 'has_archive' =&gt; false, 'hierarchical' =&gt; false, 'menu_position' =&gt; null, 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ), 'menu_icon' =&gt; 'dashicons-groups', ); register_post_type( 'doctors', $args ); } </code></pre> <p>Plugin's Code:</p> <pre><code>function cptui_register_my_cpts_doctors2() { /** * Post Type: doctors2. */ $labels = array( "name" =&gt; __( "doctors2", "understrap-child" ), "singular_name" =&gt; __( "doctor2", "understrap-child" ), ); $args = array( "label" =&gt; __( "doctors2", "understrap-child" ), "labels" =&gt; $labels, "description" =&gt; "", "public" =&gt; true, "publicly_queryable" =&gt; true, "show_ui" =&gt; true, "show_in_rest" =&gt; false, "rest_base" =&gt; "", "has_archive" =&gt; false, "show_in_menu" =&gt; true, "exclude_from_search" =&gt; false, "capability_type" =&gt; "post", "map_meta_cap" =&gt; true, "hierarchical" =&gt; false, "rewrite" =&gt; array( "slug" =&gt; "doctors2", "with_front" =&gt; true ), "query_var" =&gt; true, "supports" =&gt; array( "title", "editor", "thumbnail" ), ); register_post_type( "doctors2", $args ); } add_action( 'init', 'cptui_register_my_cpts_doctors2' ); </code></pre> <p>Any help or guidance is greatly appreciated. Thanks!</p>
[ { "answer_id": 296130, "author": "Aleksandar Mitic", "author_id": 91458, "author_profile": "https://wordpress.stackexchange.com/users/91458", "pm_score": 0, "selected": false, "text": "<p>Try this. Comment out this lines: </p>\n\n<pre><code> 'has_archive' =&gt; false,\n 'hierarchical' =&gt; false,\n</code></pre>\n\n<p>Then save permalinks in settings. Check if 404 error still appears. If not your problem is solved. You can uncomment those lines again if needed.</p>\n" }, { "answer_id": 296243, "author": "MHDavinci", "author_id": 138194, "author_profile": "https://wordpress.stackexchange.com/users/138194", "pm_score": 2, "selected": true, "text": "<p>Ok all, I think I figured out the problem...well, problemS. First, credit to @WebElaine, for putting me on the right track with the <code>unregister_post_type()</code> function. </p>\n\n<p>I unregistered ALL of my post types, then went through and made sure everything was singular with no trailing S. After unregistering everything (and commenting out any code that would register anything in the interim) I then went and refreshed my permalinks. After that, I removed the unregistering function, and uncommented my previous code and allowed things to register. This seemed to fix the issue and now the template is being read correctly.</p>\n\n<p>Thank you all for the suggestions and help. I'm a newly minted Jr Dev and am always blown away by the supportive dev community. Hope anyone who lands here with the same frustration finds this helpful!</p>\n" } ]
2018/03/07
[ "https://wordpress.stackexchange.com/questions/296129", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138194/" ]
I'm attempting to create a custom post type (doctors) that will load a custom page template (single-doctors.php). I've set up the custom post type through functions.php, and created a 'new doctor', selected the single-doctors template. But when I go to actually see the page, the template doesnt load and I'm presented with a "This page not found" page. I've been scouring the interwebs trying to find a solution to this. I find a lot of the same thing (flush permalinks, remove 'has\_archive', etc.) but nothing has worked. As a workaround, I tried downloading a custom post plugin (Custom Post Type UI) and setting things up that way. This worked!! But i will be doing more custom post creation on future sites and want to be able to do this without the plugin. I tried taking the code generated by the plugin itself and replacing my code with theirs in my functions.php file. This did not work and I was back to the "Page not found" page. I'm pulling my hair out. Can anybody help me identify what puzzle piece I'm missing? Any help is greatly appreciated. My functions.php code and the plugin's code below... My code: ``` // Doctors add_action( 'init', 'doctors_init' ); function doctors_init() { $labels = array( 'name' => _x( 'Doctors', 'post type general name', 'AIN' ), 'singular_name' => _x( 'Doctor', 'post type singular name', 'AIN' ), 'menu_name' => _x( 'Doctors', 'admin menu', 'AIN' ), 'name_admin_bar' => _x( 'Doctor', 'add new on admin bar', 'AIN' ), 'add_new' => _x( 'Add New', 'Doctor', 'AIN' ), 'add_new_item' => __( 'Add New Doctor', 'AIN' ), 'new_item' => __( 'New Doctor', 'AIN' ), 'edit_item' => __( 'Edit Doctor', 'AIN' ), 'view_item' => __( 'View Doctor', 'AIN' ), 'all_items' => __( 'All Doctors', 'AIN' ), 'search_items' => __( 'Search Doctors', 'AIN' ), 'parent_item_colon' => __( 'Parent Doctors:', 'AIN' ), 'not_found' => __( 'No Doctors found.', 'AIN' ), 'not_found_in_trash' => __( 'No Doctors found in Trash.', 'AIN' ) ); $args = array( "label" => __( "doctors", "understrap-child" ), 'labels' => $labels, 'description' => __( 'Description.', 'AIN' ), 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'doctors', "with_front" => true ), 'capability_type' => 'post', 'has_archive' => false, 'hierarchical' => false, 'menu_position' => null, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ), 'menu_icon' => 'dashicons-groups', ); register_post_type( 'doctors', $args ); } ``` Plugin's Code: ``` function cptui_register_my_cpts_doctors2() { /** * Post Type: doctors2. */ $labels = array( "name" => __( "doctors2", "understrap-child" ), "singular_name" => __( "doctor2", "understrap-child" ), ); $args = array( "label" => __( "doctors2", "understrap-child" ), "labels" => $labels, "description" => "", "public" => true, "publicly_queryable" => true, "show_ui" => true, "show_in_rest" => false, "rest_base" => "", "has_archive" => false, "show_in_menu" => true, "exclude_from_search" => false, "capability_type" => "post", "map_meta_cap" => true, "hierarchical" => false, "rewrite" => array( "slug" => "doctors2", "with_front" => true ), "query_var" => true, "supports" => array( "title", "editor", "thumbnail" ), ); register_post_type( "doctors2", $args ); } add_action( 'init', 'cptui_register_my_cpts_doctors2' ); ``` Any help or guidance is greatly appreciated. Thanks!
Ok all, I think I figured out the problem...well, problemS. First, credit to @WebElaine, for putting me on the right track with the `unregister_post_type()` function. I unregistered ALL of my post types, then went through and made sure everything was singular with no trailing S. After unregistering everything (and commenting out any code that would register anything in the interim) I then went and refreshed my permalinks. After that, I removed the unregistering function, and uncommented my previous code and allowed things to register. This seemed to fix the issue and now the template is being read correctly. Thank you all for the suggestions and help. I'm a newly minted Jr Dev and am always blown away by the supportive dev community. Hope anyone who lands here with the same frustration finds this helpful!
296,154
<p>I managed to make this shortcode work and it shows everything as I want. The only issue I am facing right now is that if I use <code>posts_per_page =&gt; 1</code>, it keeps showing all the posts. What can I do to be able to show only the latest post of the category? I tried: <code>posts_per_page =&gt; 1</code> without '', but nothing it's still not working.</p> <p>Here's the code I am using:</p> <pre><code>function Arte($atts, $content = null) { extract( shortcode_atts( array( "pagination" =&gt; 'false', "query" =&gt; '', "category" =&gt; 'arte', "posts_per_page" =&gt; '1', ), $atts ) ); global $wp_query,$paged,$post; $temp = $wp_query; $wp_query= null; $wp_query = new WP_Query(); if ( $pagination == 'true' ) { $query .= '&amp;paged='.$paged; } if (!empty($category)) { $query .= '&amp;category_name='.$category; } if (!empty($query)) { $query .= $query; } $wp_query-&gt;query($query); ob_start(); ?&gt; &lt;ul class="loop"&gt; &lt;?php while ( $wp_query-&gt;have_posts() ) : $wp_query-&gt;the_post(); ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark"&gt; &lt;div class="cont-overlay"&gt;&lt;?php the_post_thumbnail( 'ilRaccoglitore_single', array( 'class' =&gt; 'img-thumb-sidebar', 'alt' =&gt; get_the_title(), )); ?&gt; &lt;div class="overlay"&gt;&lt;/div&gt; &lt;/div&gt; &lt;h5 class="title-sidebar"&gt;&lt;?php echo the_title(); ?&gt;&lt;/h5&gt; &lt;/a&gt;&lt;/li&gt; &lt;li class="excerpt-sidebar"&gt;&lt;?php the_excerpt(); ?&gt;&lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;/ul&gt; &lt;?php if ($pagination == 'true') { ?&gt; &lt;div class="navigation"&gt; &lt;div class="alignleft"&gt;&lt;?php previous_posts_link('« Previous') ?&gt;&lt;/div&gt; &lt;div class="alignright"&gt;&lt;?php next_posts_link('More »') ?&gt;&lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;?php $wp_query = null; $wp_query = $temp; $content = ob_get_contents(); ob_end_clean(); return $content; } add_shortcode("arte", "Arte"); </code></pre> <p>Thank you in advance!</p>
[ { "answer_id": 296163, "author": "DHL17", "author_id": 125227, "author_profile": "https://wordpress.stackexchange.com/users/125227", "pm_score": 1, "selected": false, "text": "<p>For Example try this:</p>\n\n<pre><code>function my_shortcode($atts,$content=null)\n{\n extract(shortcode_atts(array(\n 'posts'=&gt;'1',\n ),$atts));\n\n $query = new WP_Query(array(\n 'posts_per_page'=&gt; $posts\n ));\n}\n\nadd_shortcode(\"latest_post\",\"my_shortcode\");\n</code></pre>\n\n<p>and add shortcode <code>[latest_post posts=1]</code></p>\n" }, { "answer_id": 296169, "author": "Xhynk", "author_id": 13724, "author_profile": "https://wordpress.stackexchange.com/users/13724", "pm_score": 1, "selected": true, "text": "<p>You have the <code>posts_per_page</code> attribute in your shortcode, but you're not actually calling it in your <code>WP_Query</code>. Your're doing a few unnecessary things in your code, but for now, the issue at hand is that you need to add:</p>\n\n<pre><code>if( !empty( $posts_per_page )) {\n $query .= '&amp;posts_per_page='.$posts_per_page;\n}\n</code></pre>\n\n<p>Before you call:</p>\n\n<pre><code>$wp_query-&gt;query($query);\n</code></pre>\n\n<p>As it is currently written, your query doesn't take into the <code>posts_per_page</code> parameter into account</p>\n" } ]
2018/03/08
[ "https://wordpress.stackexchange.com/questions/296154", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138205/" ]
I managed to make this shortcode work and it shows everything as I want. The only issue I am facing right now is that if I use `posts_per_page => 1`, it keeps showing all the posts. What can I do to be able to show only the latest post of the category? I tried: `posts_per_page => 1` without '', but nothing it's still not working. Here's the code I am using: ``` function Arte($atts, $content = null) { extract( shortcode_atts( array( "pagination" => 'false', "query" => '', "category" => 'arte', "posts_per_page" => '1', ), $atts ) ); global $wp_query,$paged,$post; $temp = $wp_query; $wp_query= null; $wp_query = new WP_Query(); if ( $pagination == 'true' ) { $query .= '&paged='.$paged; } if (!empty($category)) { $query .= '&category_name='.$category; } if (!empty($query)) { $query .= $query; } $wp_query->query($query); ob_start(); ?> <ul class="loop"> <?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?> <li><a href="<?php the_permalink() ?>" rel="bookmark"> <div class="cont-overlay"><?php the_post_thumbnail( 'ilRaccoglitore_single', array( 'class' => 'img-thumb-sidebar', 'alt' => get_the_title(), )); ?> <div class="overlay"></div> </div> <h5 class="title-sidebar"><?php echo the_title(); ?></h5> </a></li> <li class="excerpt-sidebar"><?php the_excerpt(); ?></li> <?php endwhile; ?> </ul> <?php if ($pagination == 'true') { ?> <div class="navigation"> <div class="alignleft"><?php previous_posts_link('« Previous') ?></div> <div class="alignright"><?php next_posts_link('More »') ?></div> </div> <?php } ?> <?php $wp_query = null; $wp_query = $temp; $content = ob_get_contents(); ob_end_clean(); return $content; } add_shortcode("arte", "Arte"); ``` Thank you in advance!
You have the `posts_per_page` attribute in your shortcode, but you're not actually calling it in your `WP_Query`. Your're doing a few unnecessary things in your code, but for now, the issue at hand is that you need to add: ``` if( !empty( $posts_per_page )) { $query .= '&posts_per_page='.$posts_per_page; } ``` Before you call: ``` $wp_query->query($query); ``` As it is currently written, your query doesn't take into the `posts_per_page` parameter into account
296,170
<p><strong>EDIT:</strong> <em>Based on @TimHallman's answer I have a follow-up question, please see the bottom of this post.</em></p> <p>I am trying to do something that is way over my head and the more I think of it, the more questions I end up with.</p> <p>This is the scenario I have:</p> <ul> <li>Custom posts of type <strong>golfcourse</strong>, each presenting a golf course.</li> <li>Custom posts of type <strong>clubnews</strong>.</li> <li><em>Clubnews</em> has the term <strong>clubnewsowner</strong> related to them.</li> <li><em>The clubnewsowner taxonomies are identical to the golfcourses.</em></li> </ul> <p>What I do is that (using a self made shortcode) I check, on each golfcourse-post, if one or more posts of type clubnews with taxonomy related to the spesific golfcourse exists. If yes, show the clubnews-post(s) on the golfcourse-post.</p> <p>This works as I want it to. </p> <p>I do, however, use the WP-Rocket caching plugin on this website. And because the clubnews-posts are added (to the golfcourse-posts) using php only (no ajax), WP-Rocket has no clue the content has changed on the golfcourse-post whenever a clubnews post has been added, updated or deleted. This means that I need to do a manual cache-clearing of the related golfcourse-post whenever the mentioned scenario occurs.</p> <p>Luckily, WP-Rocket has a function for this:</p> <pre><code>//clean post with ID 5 rocket_clean_post( 5 ); </code></pre> <p>I have managed to create some kind of pseudo-code:</p> <pre><code>function clearPageCacheBasedOnTaxOfClubnews() { if ( ( clubnews is created ) || ( clubnews is updated ) || ( clubnews is deleted ) ) { $customPost = clubnewsPostID; // The result here is always only one taxonomy $taxonomyOfCustompPost = get_post_taxonomies( $customPost ); switch ($taxonomyOfCustompPost) { case 'golfcourseOne': rocket_clean_post( 5 ); break; case 'golfcourseTwo': rocket_clean_post( 8 ); break; } } } add_action( 'when?', 'clearPageCacheBasedOnTaxOfClubnews', 10, ?); </code></pre> <p>I think the above code will work, but there is a lot of things I am not sure of here:</p> <ol> <li>How do I get the ID of the clubnews post being created/updated/deleted?</li> <li>How do I check if it is actually being created/updated/deleted?</li> <li>At this point my head starts spinning, and I am no longer sure what I am wondering...</li> </ol> <p>ANY help is appreciated!</p> <hr> <p><strong>Follow-up question:</strong></p> <p>I do believe @Tim Hallman solves at least two thirds of this (I need another action for when a clubnews custom post gets deleted) with his answer below. </p> <p>I, however cannot make this work. My code produces a white screen of death, whitout generating any php errors. What I think happens is that WP Rocket uses all of the resources on the server when clearing the cache on individual posts. I'm not sure though.</p> <p>This is the code:</p> <pre><code>add_action( 'save_post', 'clearPageCacheBasedOnTaxOfClubnews'); function clearPageCacheBasedOnTaxOfClubnews($post_id) { /* Is has_term() used correctly here? In the codex it says that the * taxonomy parameter is optional, other places on the Internet claims * the opposite... */ if ( has_term('clubnewsowner', '', $post_id ) { // The result here is always only one taxonomy $taxonomyOfCustompPost = get_post_taxonomies( $post_id ); /* The codex says get_post_taxonomies() returns an array. The code * on the line below produces a php fatal error though. */ $taxonomyOfCustompPost = $taxonomyOfCustompPost[0]; /* This is where the connection between the taxonomy of the * Clubnews custom posts and the golf course pages happens */ switch ($taxonomyOfCustompPost){ case 'Course One': $courseID = 123; break; case 'Course Two': $courseID = 234; break; case 'Course Three': $courseID = 345; break; ... } //This cleans the cache of the selected post rocket_clean_post( $courseID ); } } </code></pre> <p>I have tried this in different variants, and either I get a fatal error because of the $taxonomyOfCustompPost = taxonomyOfCustompPost[0]; or I get a white screen of death whitout any php errors at all.</p> <p>Any suggestions on where to go on from here?</p>
[ { "answer_id": 296175, "author": "Tim Hallman", "author_id": 38375, "author_profile": "https://wordpress.stackexchange.com/users/38375", "pm_score": 1, "selected": true, "text": "<p>I suppose a quick and dirty way to achieve what you want is to clear the entire site cache, something like this:</p>\n\n<pre><code>function clear_rocket_cache_on_post_save() {\n rocket_clean_domain();\n}\nadd_action( 'save_post', 'clear_rocket_cache_on_post_save' );\n</code></pre>\n\n<p>Otherwise you'll need to do a query to get the matching post, something like this should work:</p>\n\n<pre><code> function clear_rocket_cache_on_post_save( $post_id ) {\n\n // $result_id = tax query by $post_id\n rocket_clean_post( $result_id );\n\n }\n add_action( 'save_post', 'clear_rocket_cache_on_post_save' );\n</code></pre>\n\n<p>You can find more information on Wordpress's \"out of the box\" caching features here: <a href=\"https://codex.wordpress.org/Transients_API\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Transients_API</a></p>\n\n<p>and here: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Object_Cache\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Object_Cache</a></p>\n\n<p>Many themes do not utilize this core functionality, but it's there.</p>\n\n<p>UPDATE:</p>\n\n<p>If you're not getting debugging output on your screen, the best way to figure out why you're getting errors is to use the debug.log.</p>\n\n<p>First, put this snippet at the bottom of your <code>functions.php</code> file.</p>\n\n<pre><code>if (!function_exists('write_log')) {\n function write_log ( $log ) {\n if ( true === WP_DEBUG ) {\n if ( is_array( $log ) || is_object( $log ) ) {\n error_log( print_r( $log, true ) );\n } else {\n error_log( $log );\n }\n }\n }\n}\n</code></pre>\n\n<p>Then edit your <code>wp-config.php</code> file to include these:</p>\n\n<pre><code>define( 'WP_DEBUG', true);\ndefine( 'WP_DEBUG_DISPLAY', false );\ndefine( 'WP_DEBUG_LOG', true );\n</code></pre>\n\n<p>Then in your <code>wp-content</code> folder create a new file called <code>debug.log</code>. Now you are ready to debug.</p>\n\n<p>Now whatever you want to output you use the function <code>write_log($some_variable)</code> and it'll output your debugging errors to <code>debug.log</code>. Do that and I bet you'll see why you're getting a WSOD. /happy coding</p>\n" }, { "answer_id": 296178, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": -1, "selected": false, "text": "<p>Basically, once you start using page caching you can not do dynamic things. This is part of why wordpress do not have page caching out of the box.</p>\n\n<p>Cleaning up a page cache, especially when it is not on the server wordpress runs on, can be a long process which will make your server busier (and the whole point of having a page cache is to reduce the load).</p>\n\n<p>From your description, the problem you are facing is not a real problem, as no one will die from having some stale gulf course information, but if you just have to have it, the easier way is to reduce the time until the cache expires. This will be easier to do and you will not need to write code which is likely to have bugs and will need constant maintenance.</p>\n" }, { "answer_id": 296390, "author": "erolha", "author_id": 90832, "author_profile": "https://wordpress.stackexchange.com/users/90832", "pm_score": 0, "selected": false, "text": "<p>Ok, so I got this working. The solution is based on @TimHallman' answer below/above here. </p>\n\n<p>One of the reasons I didn't get it to work was I was confused with what is a term and what is a taxonomy. I thought a term <em>contained</em> taxonomies when it is the opposite....</p>\n\n<p>Despite good advices of not hardcoding stuff like this, not caching dynamic sites and so on there are scenarios when code like this is needed. And here is the working code:</p>\n\n<pre><code>// Run the function when a post is created or updated\nadd_action( 'save_post', 'clearPageCacheBasedOnTaxOfClubnews');\nfunction clearPageCacheBasedOnTaxOfClubnews($post_id) {\n\n $taxonomyOfCustompPost = get_post_taxonomies( $post_id );\n // In this special case, there is always only one taxonomy!\n $taxCustompPost = $taxonomyOfCustompPost[0];\n\n if ( $taxCustompPost != 'clubnewsowner' ) {\n return;\n }\n\n if ( $taxCustompPost == 'clubnewsowner' ) {\n $terms = wp_get_post_terms( $post_id, 'clubnewsowner', array(\"fields\" =&gt; \"names\"));\n $term = $terms[0];;\n\n switch ($term){\n case 'Course One': $courseID = 123; break;\n case 'Course Two': $courseID = 456; break;\n case 'Course Three': $courseID = 789; break;\n ...\n }\n\n rocket_clean_post( $courseID );\n\n\n }\n}\n\n//Run the function when the post is deleted\nadd_action('trash_post','clearPageCacheWhenCPDeleted',1,1);\nfunction clearPageCacheWhenCPDeleted($post_id){\n\n if(!did_action('trash_post')){\n\n $taxonomyOfCustompPost = get_post_taxonomies( $post_id );\n // In this special case, there is always only one taxonomy!\n $taxCustompPost = $taxonomyOfCustompPost[0];\n\n if ( $taxCustompPost != 'clubnewsowner' ) {\n return;\n }\n\n if ( $taxCustompPost == 'clubnewsowner' ) {\n\n $terms = wp_get_post_terms( $post_id, 'clubnewsowner', array(\"fields\" =&gt; \"names\"));\n $term = $terms[0];;\n\n switch ($term){\n case 'Course One': $courseID = 123; break;\n case 'Course Two': $courseID = 456; break;\n case 'Course Three': $courseID = 789; break;\n }\n\n rocket_clean_post( $courseID );\n\n }\n }\n}\n</code></pre>\n" } ]
2018/03/08
[ "https://wordpress.stackexchange.com/questions/296170", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90832/" ]
**EDIT:** *Based on @TimHallman's answer I have a follow-up question, please see the bottom of this post.* I am trying to do something that is way over my head and the more I think of it, the more questions I end up with. This is the scenario I have: * Custom posts of type **golfcourse**, each presenting a golf course. * Custom posts of type **clubnews**. * *Clubnews* has the term **clubnewsowner** related to them. * *The clubnewsowner taxonomies are identical to the golfcourses.* What I do is that (using a self made shortcode) I check, on each golfcourse-post, if one or more posts of type clubnews with taxonomy related to the spesific golfcourse exists. If yes, show the clubnews-post(s) on the golfcourse-post. This works as I want it to. I do, however, use the WP-Rocket caching plugin on this website. And because the clubnews-posts are added (to the golfcourse-posts) using php only (no ajax), WP-Rocket has no clue the content has changed on the golfcourse-post whenever a clubnews post has been added, updated or deleted. This means that I need to do a manual cache-clearing of the related golfcourse-post whenever the mentioned scenario occurs. Luckily, WP-Rocket has a function for this: ``` //clean post with ID 5 rocket_clean_post( 5 ); ``` I have managed to create some kind of pseudo-code: ``` function clearPageCacheBasedOnTaxOfClubnews() { if ( ( clubnews is created ) || ( clubnews is updated ) || ( clubnews is deleted ) ) { $customPost = clubnewsPostID; // The result here is always only one taxonomy $taxonomyOfCustompPost = get_post_taxonomies( $customPost ); switch ($taxonomyOfCustompPost) { case 'golfcourseOne': rocket_clean_post( 5 ); break; case 'golfcourseTwo': rocket_clean_post( 8 ); break; } } } add_action( 'when?', 'clearPageCacheBasedOnTaxOfClubnews', 10, ?); ``` I think the above code will work, but there is a lot of things I am not sure of here: 1. How do I get the ID of the clubnews post being created/updated/deleted? 2. How do I check if it is actually being created/updated/deleted? 3. At this point my head starts spinning, and I am no longer sure what I am wondering... ANY help is appreciated! --- **Follow-up question:** I do believe @Tim Hallman solves at least two thirds of this (I need another action for when a clubnews custom post gets deleted) with his answer below. I, however cannot make this work. My code produces a white screen of death, whitout generating any php errors. What I think happens is that WP Rocket uses all of the resources on the server when clearing the cache on individual posts. I'm not sure though. This is the code: ``` add_action( 'save_post', 'clearPageCacheBasedOnTaxOfClubnews'); function clearPageCacheBasedOnTaxOfClubnews($post_id) { /* Is has_term() used correctly here? In the codex it says that the * taxonomy parameter is optional, other places on the Internet claims * the opposite... */ if ( has_term('clubnewsowner', '', $post_id ) { // The result here is always only one taxonomy $taxonomyOfCustompPost = get_post_taxonomies( $post_id ); /* The codex says get_post_taxonomies() returns an array. The code * on the line below produces a php fatal error though. */ $taxonomyOfCustompPost = $taxonomyOfCustompPost[0]; /* This is where the connection between the taxonomy of the * Clubnews custom posts and the golf course pages happens */ switch ($taxonomyOfCustompPost){ case 'Course One': $courseID = 123; break; case 'Course Two': $courseID = 234; break; case 'Course Three': $courseID = 345; break; ... } //This cleans the cache of the selected post rocket_clean_post( $courseID ); } } ``` I have tried this in different variants, and either I get a fatal error because of the $taxonomyOfCustompPost = taxonomyOfCustompPost[0]; or I get a white screen of death whitout any php errors at all. Any suggestions on where to go on from here?
I suppose a quick and dirty way to achieve what you want is to clear the entire site cache, something like this: ``` function clear_rocket_cache_on_post_save() { rocket_clean_domain(); } add_action( 'save_post', 'clear_rocket_cache_on_post_save' ); ``` Otherwise you'll need to do a query to get the matching post, something like this should work: ``` function clear_rocket_cache_on_post_save( $post_id ) { // $result_id = tax query by $post_id rocket_clean_post( $result_id ); } add_action( 'save_post', 'clear_rocket_cache_on_post_save' ); ``` You can find more information on Wordpress's "out of the box" caching features here: <https://codex.wordpress.org/Transients_API> and here: <https://codex.wordpress.org/Class_Reference/WP_Object_Cache> Many themes do not utilize this core functionality, but it's there. UPDATE: If you're not getting debugging output on your screen, the best way to figure out why you're getting errors is to use the debug.log. First, put this snippet at the bottom of your `functions.php` file. ``` if (!function_exists('write_log')) { function write_log ( $log ) { if ( true === WP_DEBUG ) { if ( is_array( $log ) || is_object( $log ) ) { error_log( print_r( $log, true ) ); } else { error_log( $log ); } } } } ``` Then edit your `wp-config.php` file to include these: ``` define( 'WP_DEBUG', true); define( 'WP_DEBUG_DISPLAY', false ); define( 'WP_DEBUG_LOG', true ); ``` Then in your `wp-content` folder create a new file called `debug.log`. Now you are ready to debug. Now whatever you want to output you use the function `write_log($some_variable)` and it'll output your debugging errors to `debug.log`. Do that and I bet you'll see why you're getting a WSOD. /happy coding
296,184
<p>My plugin needs to store a value (timestamp) in the database. The value isn't associated with any post/page/etc. Its associated with the plugin. Where should I write this value to the database - what table?</p> <p>I've used <code>add_post_meta();</code> before and this works well to store information associated with a post/page. Is there something similar to write plugin specific information? Maybe a <code>add_plugin_meta()</code>?</p>
[ { "answer_id": 296175, "author": "Tim Hallman", "author_id": 38375, "author_profile": "https://wordpress.stackexchange.com/users/38375", "pm_score": 1, "selected": true, "text": "<p>I suppose a quick and dirty way to achieve what you want is to clear the entire site cache, something like this:</p>\n\n<pre><code>function clear_rocket_cache_on_post_save() {\n rocket_clean_domain();\n}\nadd_action( 'save_post', 'clear_rocket_cache_on_post_save' );\n</code></pre>\n\n<p>Otherwise you'll need to do a query to get the matching post, something like this should work:</p>\n\n<pre><code> function clear_rocket_cache_on_post_save( $post_id ) {\n\n // $result_id = tax query by $post_id\n rocket_clean_post( $result_id );\n\n }\n add_action( 'save_post', 'clear_rocket_cache_on_post_save' );\n</code></pre>\n\n<p>You can find more information on Wordpress's \"out of the box\" caching features here: <a href=\"https://codex.wordpress.org/Transients_API\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Transients_API</a></p>\n\n<p>and here: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Object_Cache\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Object_Cache</a></p>\n\n<p>Many themes do not utilize this core functionality, but it's there.</p>\n\n<p>UPDATE:</p>\n\n<p>If you're not getting debugging output on your screen, the best way to figure out why you're getting errors is to use the debug.log.</p>\n\n<p>First, put this snippet at the bottom of your <code>functions.php</code> file.</p>\n\n<pre><code>if (!function_exists('write_log')) {\n function write_log ( $log ) {\n if ( true === WP_DEBUG ) {\n if ( is_array( $log ) || is_object( $log ) ) {\n error_log( print_r( $log, true ) );\n } else {\n error_log( $log );\n }\n }\n }\n}\n</code></pre>\n\n<p>Then edit your <code>wp-config.php</code> file to include these:</p>\n\n<pre><code>define( 'WP_DEBUG', true);\ndefine( 'WP_DEBUG_DISPLAY', false );\ndefine( 'WP_DEBUG_LOG', true );\n</code></pre>\n\n<p>Then in your <code>wp-content</code> folder create a new file called <code>debug.log</code>. Now you are ready to debug.</p>\n\n<p>Now whatever you want to output you use the function <code>write_log($some_variable)</code> and it'll output your debugging errors to <code>debug.log</code>. Do that and I bet you'll see why you're getting a WSOD. /happy coding</p>\n" }, { "answer_id": 296178, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": -1, "selected": false, "text": "<p>Basically, once you start using page caching you can not do dynamic things. This is part of why wordpress do not have page caching out of the box.</p>\n\n<p>Cleaning up a page cache, especially when it is not on the server wordpress runs on, can be a long process which will make your server busier (and the whole point of having a page cache is to reduce the load).</p>\n\n<p>From your description, the problem you are facing is not a real problem, as no one will die from having some stale gulf course information, but if you just have to have it, the easier way is to reduce the time until the cache expires. This will be easier to do and you will not need to write code which is likely to have bugs and will need constant maintenance.</p>\n" }, { "answer_id": 296390, "author": "erolha", "author_id": 90832, "author_profile": "https://wordpress.stackexchange.com/users/90832", "pm_score": 0, "selected": false, "text": "<p>Ok, so I got this working. The solution is based on @TimHallman' answer below/above here. </p>\n\n<p>One of the reasons I didn't get it to work was I was confused with what is a term and what is a taxonomy. I thought a term <em>contained</em> taxonomies when it is the opposite....</p>\n\n<p>Despite good advices of not hardcoding stuff like this, not caching dynamic sites and so on there are scenarios when code like this is needed. And here is the working code:</p>\n\n<pre><code>// Run the function when a post is created or updated\nadd_action( 'save_post', 'clearPageCacheBasedOnTaxOfClubnews');\nfunction clearPageCacheBasedOnTaxOfClubnews($post_id) {\n\n $taxonomyOfCustompPost = get_post_taxonomies( $post_id );\n // In this special case, there is always only one taxonomy!\n $taxCustompPost = $taxonomyOfCustompPost[0];\n\n if ( $taxCustompPost != 'clubnewsowner' ) {\n return;\n }\n\n if ( $taxCustompPost == 'clubnewsowner' ) {\n $terms = wp_get_post_terms( $post_id, 'clubnewsowner', array(\"fields\" =&gt; \"names\"));\n $term = $terms[0];;\n\n switch ($term){\n case 'Course One': $courseID = 123; break;\n case 'Course Two': $courseID = 456; break;\n case 'Course Three': $courseID = 789; break;\n ...\n }\n\n rocket_clean_post( $courseID );\n\n\n }\n}\n\n//Run the function when the post is deleted\nadd_action('trash_post','clearPageCacheWhenCPDeleted',1,1);\nfunction clearPageCacheWhenCPDeleted($post_id){\n\n if(!did_action('trash_post')){\n\n $taxonomyOfCustompPost = get_post_taxonomies( $post_id );\n // In this special case, there is always only one taxonomy!\n $taxCustompPost = $taxonomyOfCustompPost[0];\n\n if ( $taxCustompPost != 'clubnewsowner' ) {\n return;\n }\n\n if ( $taxCustompPost == 'clubnewsowner' ) {\n\n $terms = wp_get_post_terms( $post_id, 'clubnewsowner', array(\"fields\" =&gt; \"names\"));\n $term = $terms[0];;\n\n switch ($term){\n case 'Course One': $courseID = 123; break;\n case 'Course Two': $courseID = 456; break;\n case 'Course Three': $courseID = 789; break;\n }\n\n rocket_clean_post( $courseID );\n\n }\n }\n}\n</code></pre>\n" } ]
2018/03/08
[ "https://wordpress.stackexchange.com/questions/296184", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75260/" ]
My plugin needs to store a value (timestamp) in the database. The value isn't associated with any post/page/etc. Its associated with the plugin. Where should I write this value to the database - what table? I've used `add_post_meta();` before and this works well to store information associated with a post/page. Is there something similar to write plugin specific information? Maybe a `add_plugin_meta()`?
I suppose a quick and dirty way to achieve what you want is to clear the entire site cache, something like this: ``` function clear_rocket_cache_on_post_save() { rocket_clean_domain(); } add_action( 'save_post', 'clear_rocket_cache_on_post_save' ); ``` Otherwise you'll need to do a query to get the matching post, something like this should work: ``` function clear_rocket_cache_on_post_save( $post_id ) { // $result_id = tax query by $post_id rocket_clean_post( $result_id ); } add_action( 'save_post', 'clear_rocket_cache_on_post_save' ); ``` You can find more information on Wordpress's "out of the box" caching features here: <https://codex.wordpress.org/Transients_API> and here: <https://codex.wordpress.org/Class_Reference/WP_Object_Cache> Many themes do not utilize this core functionality, but it's there. UPDATE: If you're not getting debugging output on your screen, the best way to figure out why you're getting errors is to use the debug.log. First, put this snippet at the bottom of your `functions.php` file. ``` if (!function_exists('write_log')) { function write_log ( $log ) { if ( true === WP_DEBUG ) { if ( is_array( $log ) || is_object( $log ) ) { error_log( print_r( $log, true ) ); } else { error_log( $log ); } } } } ``` Then edit your `wp-config.php` file to include these: ``` define( 'WP_DEBUG', true); define( 'WP_DEBUG_DISPLAY', false ); define( 'WP_DEBUG_LOG', true ); ``` Then in your `wp-content` folder create a new file called `debug.log`. Now you are ready to debug. Now whatever you want to output you use the function `write_log($some_variable)` and it'll output your debugging errors to `debug.log`. Do that and I bet you'll see why you're getting a WSOD. /happy coding
296,194
<p>My WordPress debug.log is filling up with this group of seven PHP warnings/notices, recurring at least every half an hour...</p> <pre><code>[08-Mar-2018 09:05:03 UTC] PHP Notice: Trying to get property of non-object in /home/mysite/public_html/wp-includes/class-wp-query.php on line 3736 [08-Mar-2018 09:05:03 UTC] PHP Notice: Trying to get property of non-object in /home/mysite/public_html/wp-includes/class-wp-query.php on line 3738 [08-Mar-2018 09:05:03 UTC] PHP Notice: Trying to get property of non-object in /home/mysite/public_html/wp-includes/class-wp-query.php on line 3740 [08-Mar-2018 09:05:03 UTC] PHP Notice: Trying to get property of non-object in /home/mysite/public_html/wp-includes/class-wp-query.php on line 3736 [08-Mar-2018 09:05:03 UTC] PHP Notice: Trying to get property of non-object in /home/mysite/public_html/wp-includes/class-wp-query.php on line 3738 [08-Mar-2018 09:05:03 UTC] PHP Notice: Trying to get property of non-object in /home/mysite/public_html/wp-includes/class-wp-query.php on line 3740 [08-Mar-2018 09:05:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /home/mysite/public_html/wp-includes/class-wp-query.php:3736) in /home/mysite/public_html/wp-includes/pluggable.php on line 1216 </code></pre> <p>The trouble is, as far as I can see, there is no reference to which plugin or culprit is causing this (I think the term for this is, there is no back trace / stack trace), so I'm finding it hard to debug.</p> <p>The question is: <strong>How can I find out more detail in order to trace the cause?</strong></p> <p>I already have <code>WP_DEBUG</code>, <code>WP_DEBUG</code> and <code>WP_DEBUG_DISPLAY</code> all set to true.</p> <p>I have looked in to setting PHP <code>display_errors</code> and <code>error_reporting</code> but, since I am already getting notices and warnings output, I am not sure whether these settings would add any more detail.</p> <p>Is it possible these warnings are being generated by a non-WordPress plugin? I do have a PHP script operating on cron which invokes the wpdb environment but which is not strictly a plugin.</p>
[ { "answer_id": 332654, "author": "Ted Stresen-Reuter", "author_id": 112766, "author_profile": "https://wordpress.stackexchange.com/users/112766", "pm_score": 3, "selected": false, "text": "<p>You can get the backtrace by trapping the E_NOTICE message. If you add the following snippet to wp-config.php just before </p>\n\n<pre><code>/* That's all, stop editing! Happy blogging. */\n</code></pre>\n\n<p>you should see the full backtrace in the error log.</p>\n\n<pre><code>set_error_handler(function() {\n error_log(print_r(debug_backtrace(), true));\n return true;\n}, E_USER_NOTICE);\n\ndefine( 'WP_DEBUG', true );\ndefine( 'WP_DEBUG_LOG', true );\ndefine( 'WP_DEBUG_DISPLAY', false );\n\n/* That's all, stop editing! Happy blogging. */\n</code></pre>\n\n<p>PS: Returning <code>true</code> at the end of the function tells PHP to stop processing the E_NOTICE, which is probably what you want at this point.</p>\n\n<p>I <em>just</em> used this approach on a project and it was exactly the solution I was looking for. In fact, I found this post while looking for a way to do the same thing. Happy sailing!</p>\n" }, { "answer_id": 399321, "author": "squarecandy", "author_id": 41488, "author_profile": "https://wordpress.stackexchange.com/users/41488", "pm_score": 2, "selected": false, "text": "<p>Ted's answer worked great for me, but was super verbose, making it both hard to read and easy to accidentally create a massive log file if you left it on accidentally.</p>\n<p>I ended up using this for a more concise log entry:</p>\n<pre><code>set_error_handler(function() {\n $log = &quot;\\r\\n==========\\r\\nSTACK TRACE:&quot;;\n foreach ( debug_backtrace() as $i =&gt; $item ) {\n if ( 0 === $i ) {\n $log .= &quot;\\r\\n&quot; . $item['args'][1];\n } else {\n $log .= &quot;\\r\\n&quot; . $item['file'] . ' -- line ' . $item['line'];\n }\n }\n $log .= &quot;\\r\\n==========&quot;;\n error_log( $log );\n return true;\n}, E_USER_NOTICE);\n\ndefine( 'WP_DEBUG', true );\ndefine( 'WP_DEBUG_LOG', true );\n</code></pre>\n<p>This cut the particular error I was looking at down from 13,000 lines in my log file to around 20, and allowed me to quickly identify which plugin was the culprit.</p>\n" } ]
2018/03/08
[ "https://wordpress.stackexchange.com/questions/296194", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/39300/" ]
My WordPress debug.log is filling up with this group of seven PHP warnings/notices, recurring at least every half an hour... ``` [08-Mar-2018 09:05:03 UTC] PHP Notice: Trying to get property of non-object in /home/mysite/public_html/wp-includes/class-wp-query.php on line 3736 [08-Mar-2018 09:05:03 UTC] PHP Notice: Trying to get property of non-object in /home/mysite/public_html/wp-includes/class-wp-query.php on line 3738 [08-Mar-2018 09:05:03 UTC] PHP Notice: Trying to get property of non-object in /home/mysite/public_html/wp-includes/class-wp-query.php on line 3740 [08-Mar-2018 09:05:03 UTC] PHP Notice: Trying to get property of non-object in /home/mysite/public_html/wp-includes/class-wp-query.php on line 3736 [08-Mar-2018 09:05:03 UTC] PHP Notice: Trying to get property of non-object in /home/mysite/public_html/wp-includes/class-wp-query.php on line 3738 [08-Mar-2018 09:05:03 UTC] PHP Notice: Trying to get property of non-object in /home/mysite/public_html/wp-includes/class-wp-query.php on line 3740 [08-Mar-2018 09:05:03 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /home/mysite/public_html/wp-includes/class-wp-query.php:3736) in /home/mysite/public_html/wp-includes/pluggable.php on line 1216 ``` The trouble is, as far as I can see, there is no reference to which plugin or culprit is causing this (I think the term for this is, there is no back trace / stack trace), so I'm finding it hard to debug. The question is: **How can I find out more detail in order to trace the cause?** I already have `WP_DEBUG`, `WP_DEBUG` and `WP_DEBUG_DISPLAY` all set to true. I have looked in to setting PHP `display_errors` and `error_reporting` but, since I am already getting notices and warnings output, I am not sure whether these settings would add any more detail. Is it possible these warnings are being generated by a non-WordPress plugin? I do have a PHP script operating on cron which invokes the wpdb environment but which is not strictly a plugin.
You can get the backtrace by trapping the E\_NOTICE message. If you add the following snippet to wp-config.php just before ``` /* That's all, stop editing! Happy blogging. */ ``` you should see the full backtrace in the error log. ``` set_error_handler(function() { error_log(print_r(debug_backtrace(), true)); return true; }, E_USER_NOTICE); define( 'WP_DEBUG', true ); define( 'WP_DEBUG_LOG', true ); define( 'WP_DEBUG_DISPLAY', false ); /* That's all, stop editing! Happy blogging. */ ``` PS: Returning `true` at the end of the function tells PHP to stop processing the E\_NOTICE, which is probably what you want at this point. I *just* used this approach on a project and it was exactly the solution I was looking for. In fact, I found this post while looking for a way to do the same thing. Happy sailing!
296,248
<p>I wrote this simple code to prove what I'm saying:</p> <pre><code>wp_nav_menu( [ 'menu' =&gt; 'Primary Navigation', 'menu_class' =&gt; 'this-is-the-menu-class', 'menu_id' =&gt; 'this-is-the-menu-id', 'container' =&gt; 'div', 'container_class' =&gt; 'this-is-the-container-class', 'container_id' =&gt; 'this-is-the-container-ID', ] ); </code></pre> <p>This is the output:</p> <pre><code>&lt;div id="this-is-the-menu-id" class="this-is-the-menu-class"&gt; &lt;ul&gt; &lt;li class="page_item page-item-2"&gt; &lt;a href="http://localhost/test_site/index.php/pagina-di-esempio/"&gt;Example Page.&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p><strong>As you can see the <code>ul</code> element doesn't receive any class nor ID.</strong></p> <p><strong>They, instead, are applied to the container and the container classes and ID seem to be simply missed (or getting the default values).</strong></p> <p>In the documentation is told that</p> <blockquote> <ul> <li>'menu_class' (string) CSS class to use for the ul element which forms the menu. Default 'menu'.</li> <li>'menu_id' (string) The ID that is applied to the ul element which forms the menu. Default is the menu slug, incremented.</li> <li>'container' (string) Whether to wrap the ul, and what to wrap it with. Default 'div'.</li> <li>'container_class' (string) Class that is applied to the container. Default 'menu-{menu slug}-container'.</li> <li>'container_id' (string) The ID that is applied to the container.</li> </ul> </blockquote> <p><strong>But as you can see the result is not the one expected.</strong></p> <p>In <a href="https://wordpress.stackexchange.com/questions/253192/container-class-doesnt-seem-to-be-working">this discussion</a> the user set wrong the <code>container</code> param, and so the replies point out this error, but the error still exists and I'm doing all following the rules (at least I think!).</p> <p><strong>Am I doing something wrong or effectively the function is bugged?</strong></p> <p>NOTEs:</p> <ul> <li>I'm using Genesis Framework (just in case it may be useful to understand the context)</li> <li>Wordpress version is <code>4.9.4</code></li> </ul>
[ { "answer_id": 296253, "author": "sMyles", "author_id": 51201, "author_profile": "https://wordpress.stackexchange.com/users/51201", "pm_score": 4, "selected": true, "text": "<p>I believe this is caused probably by your theme or another plugin, filtering on <code>wp_nav_menu_args</code> and changing the <code>items_wrap</code> value. I tested your provided code and the output was correct, using blank WordPress 4.9.4 installation.</p>\n\n<p>You could try passing <code>items_wrap</code> with default value:</p>\n\n<pre><code>wp_nav_menu( [\n 'menu' =&gt; 'Primary Navigation',\n 'menu_class' =&gt; 'this-is-the-menu-class',\n 'menu_id' =&gt; 'this-is-the-menu-id',\n 'container' =&gt; 'div',\n 'container_class' =&gt; 'this-is-the-container-class',\n 'container_id' =&gt; 'this-is-the-container-ID',\n 'items_wrap' =&gt; '&lt;ul id=\"%1$s\" class=\"%2$s\"&gt;%3$s&lt;/ul&gt;'\n] );\n</code></pre>\n\n<p>But if something is filtering that out, it wouldn't make a difference.</p>\n\n<p>I recommend adding this to your child theme's functions.php file, to remove all filters and see if that fixes it (to prove it is a filter causing your problem):</p>\n\n<pre><code>remove_all_filters( 'wp_nav_menu_args' );\n</code></pre>\n\n<p>You can also add this to your child theme's functions.php, to dump out on screen, the <code>$args</code> array, where you can check the value of <code>items_wrap</code>:</p>\n\n<pre><code>add_filter( 'pre_wp_nav_menu', 'smyles_dump_nav_menu_args', 9999, 2 );\n\nfunction smyles_dump_nav_menu_args( $null, $args ){\n ob_start();\n\n echo '&lt;pre&gt;';\n var_dump($args);\n echo '&lt;/pre&gt;';\n\n $content = ob_get_contents();\n ob_end_clean();\n return $content;\n}\n</code></pre>\n\n<p>Returning a true value (in our case, it's HTML) to this filter will cause it to echo on page, when <code>echo</code> is passed true in the <code>wp_nav_menu</code></p>\n\n<p>Make sure to add <code>echo</code> and set <code>true</code> in <code>wp_nav_menu</code> call:</p>\n\n<pre><code>wp_nav_menu( [\n 'menu' =&gt; 'Primary Navigation',\n 'menu_class' =&gt; 'this-is-the-menu-class',\n 'menu_id' =&gt; 'this-is-the-menu-id',\n 'container' =&gt; 'div',\n 'container_class' =&gt; 'this-is-the-container-class',\n 'container_id' =&gt; 'this-is-the-container-ID',\n 'echo' =&gt; true\n] );\n</code></pre>\n" }, { "answer_id": 344848, "author": "user173315", "author_id": 173315, "author_profile": "https://wordpress.stackexchange.com/users/173315", "pm_score": -1, "selected": false, "text": "<p>I had this same problem and came to the conclusion that this was happening because I had not created the menu in the wordpress admin panel.</p>\n\n<p>What you have to do is <strong>create a menu</strong> in the admin panel and use that menu to locate the menu you created in the code.</p>\n" }, { "answer_id": 411376, "author": "Lucas", "author_id": 227584, "author_profile": "https://wordpress.stackexchange.com/users/227584", "pm_score": -1, "selected": false, "text": "<p>Just ran into this <strong>exact</strong> problem : the menu_class going on the container and the ul having no class at all.</p>\n<p>Turns out this was due to me forgetting to check a menu location when creating the menu in my admin panel.</p>\n<p>Instead of giving you an error, wordpress uses a default menu location and for some weird behind-the-scene reason it causes this.</p>\n" } ]
2018/03/08
[ "https://wordpress.stackexchange.com/questions/296248", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57145/" ]
I wrote this simple code to prove what I'm saying: ``` wp_nav_menu( [ 'menu' => 'Primary Navigation', 'menu_class' => 'this-is-the-menu-class', 'menu_id' => 'this-is-the-menu-id', 'container' => 'div', 'container_class' => 'this-is-the-container-class', 'container_id' => 'this-is-the-container-ID', ] ); ``` This is the output: ``` <div id="this-is-the-menu-id" class="this-is-the-menu-class"> <ul> <li class="page_item page-item-2"> <a href="http://localhost/test_site/index.php/pagina-di-esempio/">Example Page.</a> </li> </ul> </div> ``` **As you can see the `ul` element doesn't receive any class nor ID.** **They, instead, are applied to the container and the container classes and ID seem to be simply missed (or getting the default values).** In the documentation is told that > > * 'menu\_class' (string) CSS class to use for the ul element which forms the menu. Default 'menu'. > * 'menu\_id' (string) The ID that is applied to the ul element which forms the menu. Default is the menu slug, incremented. > * 'container' (string) Whether to wrap the ul, and what to wrap it with. Default 'div'. > * 'container\_class' (string) Class that is applied to the container. Default 'menu-{menu slug}-container'. > * 'container\_id' (string) The ID that is applied to the container. > > > **But as you can see the result is not the one expected.** In [this discussion](https://wordpress.stackexchange.com/questions/253192/container-class-doesnt-seem-to-be-working) the user set wrong the `container` param, and so the replies point out this error, but the error still exists and I'm doing all following the rules (at least I think!). **Am I doing something wrong or effectively the function is bugged?** NOTEs: * I'm using Genesis Framework (just in case it may be useful to understand the context) * Wordpress version is `4.9.4`
I believe this is caused probably by your theme or another plugin, filtering on `wp_nav_menu_args` and changing the `items_wrap` value. I tested your provided code and the output was correct, using blank WordPress 4.9.4 installation. You could try passing `items_wrap` with default value: ``` wp_nav_menu( [ 'menu' => 'Primary Navigation', 'menu_class' => 'this-is-the-menu-class', 'menu_id' => 'this-is-the-menu-id', 'container' => 'div', 'container_class' => 'this-is-the-container-class', 'container_id' => 'this-is-the-container-ID', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>' ] ); ``` But if something is filtering that out, it wouldn't make a difference. I recommend adding this to your child theme's functions.php file, to remove all filters and see if that fixes it (to prove it is a filter causing your problem): ``` remove_all_filters( 'wp_nav_menu_args' ); ``` You can also add this to your child theme's functions.php, to dump out on screen, the `$args` array, where you can check the value of `items_wrap`: ``` add_filter( 'pre_wp_nav_menu', 'smyles_dump_nav_menu_args', 9999, 2 ); function smyles_dump_nav_menu_args( $null, $args ){ ob_start(); echo '<pre>'; var_dump($args); echo '</pre>'; $content = ob_get_contents(); ob_end_clean(); return $content; } ``` Returning a true value (in our case, it's HTML) to this filter will cause it to echo on page, when `echo` is passed true in the `wp_nav_menu` Make sure to add `echo` and set `true` in `wp_nav_menu` call: ``` wp_nav_menu( [ 'menu' => 'Primary Navigation', 'menu_class' => 'this-is-the-menu-class', 'menu_id' => 'this-is-the-menu-id', 'container' => 'div', 'container_class' => 'this-is-the-container-class', 'container_id' => 'this-is-the-container-ID', 'echo' => true ] ); ```
296,303
<p>How do I prevent the creation of these when creating a new Multisite?</p> <p>Everytime I create a new multisite this gets created:</p> <ul> <li>Hello World</li> <li>Sample Page</li> <li>A sample Comment</li> </ul> <p>I tried adding this to the <code>functions.php</code></p> <pre><code>add_action( 'wpmu_new_blog', 'delete_wordpress_defaults', 100, 1 ); function delete_wordpress_defaults(){ // 'Hello World!' post wp_delete_post( 1, true ); // 'Sample page' page wp_delete_post( 2, true ); } </code></pre> <p>It still created Hello world and Sample page. And I don't know how to disable the sample comment.</p>
[ { "answer_id": 296306, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>When you <a href=\"https://developer.wordpress.org/reference/functions/wpmu_create_blog/\" rel=\"nofollow noreferrer\">create a new site with multisite</a> WP does not automatically change the context. So your action is added to the current site, not the new site. You have to switch first. Like this:</p>\n\n<pre><code>add_action ('wpmu_new_blog', 'wpse296303_delete_wordpress_defaults', 100, 1);\n\nfunction wpse296303_delete_wordpress_defaults ($blog_id, $user_id, $domain, $path, $site_id, $meta) {\n // Switch to the newly created blog\n switch_to_blog ($blog_id);\n // Delete 'Hello World!' post\n wp_delete_post (1, true);\n // Delete 'Sample page' page\n wp_delete_post (2, true);\n // Delete 'Sample comment' page\n wp_delete_comment (1, true)\n }\n</code></pre>\n\n<p>I'm not sure if the ID of the default comment is 1, so you'd have to check that.</p>\n" }, { "answer_id": 400948, "author": "Barzdotas Oziukas", "author_id": 217513, "author_profile": "https://wordpress.stackexchange.com/users/217513", "pm_score": 0, "selected": false, "text": "<p>best luck i got:</p>\n<p>/public_html/wp-includes/widgets/class-wp-widget-meta.php\n\\public_html\\wp-admin\\includes\\schema.php\n/public_html\\wp-admin\\includes\\upgrade.php</p>\n<p>deleteing code of post comment page url etc.\n5.1.11</p>\n<p>yes after update they might be restored but you will know where to fix up again.</p>\n" } ]
2018/03/09
[ "https://wordpress.stackexchange.com/questions/296303", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138051/" ]
How do I prevent the creation of these when creating a new Multisite? Everytime I create a new multisite this gets created: * Hello World * Sample Page * A sample Comment I tried adding this to the `functions.php` ``` add_action( 'wpmu_new_blog', 'delete_wordpress_defaults', 100, 1 ); function delete_wordpress_defaults(){ // 'Hello World!' post wp_delete_post( 1, true ); // 'Sample page' page wp_delete_post( 2, true ); } ``` It still created Hello world and Sample page. And I don't know how to disable the sample comment.
When you [create a new site with multisite](https://developer.wordpress.org/reference/functions/wpmu_create_blog/) WP does not automatically change the context. So your action is added to the current site, not the new site. You have to switch first. Like this: ``` add_action ('wpmu_new_blog', 'wpse296303_delete_wordpress_defaults', 100, 1); function wpse296303_delete_wordpress_defaults ($blog_id, $user_id, $domain, $path, $site_id, $meta) { // Switch to the newly created blog switch_to_blog ($blog_id); // Delete 'Hello World!' post wp_delete_post (1, true); // Delete 'Sample page' page wp_delete_post (2, true); // Delete 'Sample comment' page wp_delete_comment (1, true) } ``` I'm not sure if the ID of the default comment is 1, so you'd have to check that.
296,308
<p>I want to replace the following message when creating a user in the dashboard as an administrator: </p> <pre><code>Username: xxx To set your password, visit the following address: https://development.xxx.com/wp-login.php?action=rp&amp;key=FlFdsDeAveg2EN1HuqGB0G&amp;login=xxx%40gmail.com https://development.xxx.com/wp-login.php </code></pre> <p>This is my non-working function: </p> <pre><code>/** * Custom Welcome Email * @author Archie M * */ add_filter( 'wpmu_signup_user_notification_subject', 'my_activation_subject', 10, 4 ); function my_activation_subject( $text ) { return 'Welcome to xxx! (Activation required)'; } add_filter('wpmu_signup_user_notification_email', 'my_custom_email_message', 10, 4); function my_custom_email_message($message, $user, $user_email, $key) { //Here is the new message: $message = sprintf(__('Hi %s'), $user-&gt;display_name) . "\r\n\r\n"; $message .= __('Your registration on xxx has been approved.') . "\r\n\r\n"; $message .= __('To set your password, visit the following address:') . "\r\n\r\n"; $message .= '&lt;' . network_site_url("wp-login.php?action=rp&amp;key=$key&amp;login=" . rawurlencode($user-&gt;user_login), 'login') . "&gt;\r\n\r\n"; return sprintf($message); } </code></pre> <p>Where exactly am I missing the point?</p>
[ { "answer_id": 296306, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>When you <a href=\"https://developer.wordpress.org/reference/functions/wpmu_create_blog/\" rel=\"nofollow noreferrer\">create a new site with multisite</a> WP does not automatically change the context. So your action is added to the current site, not the new site. You have to switch first. Like this:</p>\n\n<pre><code>add_action ('wpmu_new_blog', 'wpse296303_delete_wordpress_defaults', 100, 1);\n\nfunction wpse296303_delete_wordpress_defaults ($blog_id, $user_id, $domain, $path, $site_id, $meta) {\n // Switch to the newly created blog\n switch_to_blog ($blog_id);\n // Delete 'Hello World!' post\n wp_delete_post (1, true);\n // Delete 'Sample page' page\n wp_delete_post (2, true);\n // Delete 'Sample comment' page\n wp_delete_comment (1, true)\n }\n</code></pre>\n\n<p>I'm not sure if the ID of the default comment is 1, so you'd have to check that.</p>\n" }, { "answer_id": 400948, "author": "Barzdotas Oziukas", "author_id": 217513, "author_profile": "https://wordpress.stackexchange.com/users/217513", "pm_score": 0, "selected": false, "text": "<p>best luck i got:</p>\n<p>/public_html/wp-includes/widgets/class-wp-widget-meta.php\n\\public_html\\wp-admin\\includes\\schema.php\n/public_html\\wp-admin\\includes\\upgrade.php</p>\n<p>deleteing code of post comment page url etc.\n5.1.11</p>\n<p>yes after update they might be restored but you will know where to fix up again.</p>\n" } ]
2018/03/09
[ "https://wordpress.stackexchange.com/questions/296308", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I want to replace the following message when creating a user in the dashboard as an administrator: ``` Username: xxx To set your password, visit the following address: https://development.xxx.com/wp-login.php?action=rp&key=FlFdsDeAveg2EN1HuqGB0G&login=xxx%40gmail.com https://development.xxx.com/wp-login.php ``` This is my non-working function: ``` /** * Custom Welcome Email * @author Archie M * */ add_filter( 'wpmu_signup_user_notification_subject', 'my_activation_subject', 10, 4 ); function my_activation_subject( $text ) { return 'Welcome to xxx! (Activation required)'; } add_filter('wpmu_signup_user_notification_email', 'my_custom_email_message', 10, 4); function my_custom_email_message($message, $user, $user_email, $key) { //Here is the new message: $message = sprintf(__('Hi %s'), $user->display_name) . "\r\n\r\n"; $message .= __('Your registration on xxx has been approved.') . "\r\n\r\n"; $message .= __('To set your password, visit the following address:') . "\r\n\r\n"; $message .= '<' . network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user->user_login), 'login') . ">\r\n\r\n"; return sprintf($message); } ``` Where exactly am I missing the point?
When you [create a new site with multisite](https://developer.wordpress.org/reference/functions/wpmu_create_blog/) WP does not automatically change the context. So your action is added to the current site, not the new site. You have to switch first. Like this: ``` add_action ('wpmu_new_blog', 'wpse296303_delete_wordpress_defaults', 100, 1); function wpse296303_delete_wordpress_defaults ($blog_id, $user_id, $domain, $path, $site_id, $meta) { // Switch to the newly created blog switch_to_blog ($blog_id); // Delete 'Hello World!' post wp_delete_post (1, true); // Delete 'Sample page' page wp_delete_post (2, true); // Delete 'Sample comment' page wp_delete_comment (1, true) } ``` I'm not sure if the ID of the default comment is 1, so you'd have to check that.
296,320
<p>I am trying to list posts in a widget I am working on at the moment. However, when I use the get_template_part function in my loop, my site just keeps loading until I get a 500 http error.</p> <pre><code> $args = array( 'numberposts' =&gt; 10, 'orderby' =&gt; 'date', 'order' =&gt; 'DESC', 'post_type' =&gt; $postType, 'suppress_filters' =&gt; true ); $postsQuery = new WP_Query( $args ); if ( $postsQuery-&gt;have_posts() ) { while ( $postsQuery-&gt;have_posts() ) { get_template_part( 'content/content', $postType ); } /* Restore original Post Data */ wp_reset_postdata(); } </code></pre> <p>When I comment the <code>get_template_part</code> out, everything works just fine. Also the loop seems to loop perfectly through the posts. Just the <code>get_template_part</code> is somewhat problematic. I don't have any idea, how I could figure out what the problem is. Any ideas? Maybe I am using it wrong or something?</p> <hr> <p>Here's the solution:</p> <p>I was missing the <code>$postsQuery-&gt;the_post()</code> in my loop. Also guilemons tip helped, that I needed a folder called content in the same directory where my php file was with the templates.</p>
[ { "answer_id": 296306, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>When you <a href=\"https://developer.wordpress.org/reference/functions/wpmu_create_blog/\" rel=\"nofollow noreferrer\">create a new site with multisite</a> WP does not automatically change the context. So your action is added to the current site, not the new site. You have to switch first. Like this:</p>\n\n<pre><code>add_action ('wpmu_new_blog', 'wpse296303_delete_wordpress_defaults', 100, 1);\n\nfunction wpse296303_delete_wordpress_defaults ($blog_id, $user_id, $domain, $path, $site_id, $meta) {\n // Switch to the newly created blog\n switch_to_blog ($blog_id);\n // Delete 'Hello World!' post\n wp_delete_post (1, true);\n // Delete 'Sample page' page\n wp_delete_post (2, true);\n // Delete 'Sample comment' page\n wp_delete_comment (1, true)\n }\n</code></pre>\n\n<p>I'm not sure if the ID of the default comment is 1, so you'd have to check that.</p>\n" }, { "answer_id": 400948, "author": "Barzdotas Oziukas", "author_id": 217513, "author_profile": "https://wordpress.stackexchange.com/users/217513", "pm_score": 0, "selected": false, "text": "<p>best luck i got:</p>\n<p>/public_html/wp-includes/widgets/class-wp-widget-meta.php\n\\public_html\\wp-admin\\includes\\schema.php\n/public_html\\wp-admin\\includes\\upgrade.php</p>\n<p>deleteing code of post comment page url etc.\n5.1.11</p>\n<p>yes after update they might be restored but you will know where to fix up again.</p>\n" } ]
2018/03/09
[ "https://wordpress.stackexchange.com/questions/296320", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118091/" ]
I am trying to list posts in a widget I am working on at the moment. However, when I use the get\_template\_part function in my loop, my site just keeps loading until I get a 500 http error. ``` $args = array( 'numberposts' => 10, 'orderby' => 'date', 'order' => 'DESC', 'post_type' => $postType, 'suppress_filters' => true ); $postsQuery = new WP_Query( $args ); if ( $postsQuery->have_posts() ) { while ( $postsQuery->have_posts() ) { get_template_part( 'content/content', $postType ); } /* Restore original Post Data */ wp_reset_postdata(); } ``` When I comment the `get_template_part` out, everything works just fine. Also the loop seems to loop perfectly through the posts. Just the `get_template_part` is somewhat problematic. I don't have any idea, how I could figure out what the problem is. Any ideas? Maybe I am using it wrong or something? --- Here's the solution: I was missing the `$postsQuery->the_post()` in my loop. Also guilemons tip helped, that I needed a folder called content in the same directory where my php file was with the templates.
When you [create a new site with multisite](https://developer.wordpress.org/reference/functions/wpmu_create_blog/) WP does not automatically change the context. So your action is added to the current site, not the new site. You have to switch first. Like this: ``` add_action ('wpmu_new_blog', 'wpse296303_delete_wordpress_defaults', 100, 1); function wpse296303_delete_wordpress_defaults ($blog_id, $user_id, $domain, $path, $site_id, $meta) { // Switch to the newly created blog switch_to_blog ($blog_id); // Delete 'Hello World!' post wp_delete_post (1, true); // Delete 'Sample page' page wp_delete_post (2, true); // Delete 'Sample comment' page wp_delete_comment (1, true) } ``` I'm not sure if the ID of the default comment is 1, so you'd have to check that.
296,341
<p>Is it possible to use WordPress to serve up a hard coded page that already exists? The goal is that we want to make some simple shorter urls but not have a huge mess in the root directory of our website.</p>
[ { "answer_id": 296306, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>When you <a href=\"https://developer.wordpress.org/reference/functions/wpmu_create_blog/\" rel=\"nofollow noreferrer\">create a new site with multisite</a> WP does not automatically change the context. So your action is added to the current site, not the new site. You have to switch first. Like this:</p>\n\n<pre><code>add_action ('wpmu_new_blog', 'wpse296303_delete_wordpress_defaults', 100, 1);\n\nfunction wpse296303_delete_wordpress_defaults ($blog_id, $user_id, $domain, $path, $site_id, $meta) {\n // Switch to the newly created blog\n switch_to_blog ($blog_id);\n // Delete 'Hello World!' post\n wp_delete_post (1, true);\n // Delete 'Sample page' page\n wp_delete_post (2, true);\n // Delete 'Sample comment' page\n wp_delete_comment (1, true)\n }\n</code></pre>\n\n<p>I'm not sure if the ID of the default comment is 1, so you'd have to check that.</p>\n" }, { "answer_id": 400948, "author": "Barzdotas Oziukas", "author_id": 217513, "author_profile": "https://wordpress.stackexchange.com/users/217513", "pm_score": 0, "selected": false, "text": "<p>best luck i got:</p>\n<p>/public_html/wp-includes/widgets/class-wp-widget-meta.php\n\\public_html\\wp-admin\\includes\\schema.php\n/public_html\\wp-admin\\includes\\upgrade.php</p>\n<p>deleteing code of post comment page url etc.\n5.1.11</p>\n<p>yes after update they might be restored but you will know where to fix up again.</p>\n" } ]
2018/03/09
[ "https://wordpress.stackexchange.com/questions/296341", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138324/" ]
Is it possible to use WordPress to serve up a hard coded page that already exists? The goal is that we want to make some simple shorter urls but not have a huge mess in the root directory of our website.
When you [create a new site with multisite](https://developer.wordpress.org/reference/functions/wpmu_create_blog/) WP does not automatically change the context. So your action is added to the current site, not the new site. You have to switch first. Like this: ``` add_action ('wpmu_new_blog', 'wpse296303_delete_wordpress_defaults', 100, 1); function wpse296303_delete_wordpress_defaults ($blog_id, $user_id, $domain, $path, $site_id, $meta) { // Switch to the newly created blog switch_to_blog ($blog_id); // Delete 'Hello World!' post wp_delete_post (1, true); // Delete 'Sample page' page wp_delete_post (2, true); // Delete 'Sample comment' page wp_delete_comment (1, true) } ``` I'm not sure if the ID of the default comment is 1, so you'd have to check that.
296,366
<p>I have created a small shortcode function with attributes to review if attributes are handled properly. That's the case and now I would like to use the attribute in a SELECT statement. But the database does not provide any values. The SQL statement without variable in the WHERE condition is okay. </p> <p>To test shortcodes, I've added this three lines into my Wordpress text page, but nor of them is working:</p> <pre><code> [simplelist text=Beatles] [simplelist text='Beatles'] [simplelist text="Beatles"] </code></pre> <p>And here is my code from functions.php: </p> <pre><code> &lt;?php .... function get_list( $atts ) { $atts = shortcode_atts( array( 'text' =&gt; '', ), $atts); global $wpdb; $simplelist = $wpdb-&gt;get_results("SELECT `Row1`, `Row2` FROM `table` WHERE `Row1` = " . $atts[text] . " ORDER BY `Row1` ASC"); $Result = .... some stuff here ... return $Result; } add_shortcode('simplelist', 'get_list' ); ?&gt; </code></pre> <p>When I remove the WHERE condition, I get complete table results. I need some help in using attribute values in WHERE condition. </p>
[ { "answer_id": 296370, "author": "J.BizMai", "author_id": 128094, "author_profile": "https://wordpress.stackexchange.com/users/128094", "pm_score": -1, "selected": false, "text": "<p>First of all, you seem to get a mysql error. <code>$attr[text]</code> is a string so you need to wrap it with simple quote:</p>\n\n<blockquote>\n <p><code>Row1 = '{$atts[text]}'</code> </p>\n</blockquote>\n\n<p>Then, the <code>$wpdb-&gt;get_results()</code> function return by default an object.</p>\n\n<p>If you want a PHP array as result :</p>\n\n<blockquote>\n <p>use <code>ARRAY_A</code> as second argument like this : <code>$wpdb-&gt;get_results( $query, ARRAY_A );</code></p>\n</blockquote>\n\n<p><strong>Complete function</strong></p>\n\n<pre><code>function get_list( $atts )\n{ \n $atts = shortcode_atts( array(\n 'text' =&gt; '',\n ), \n $atts );\n\n\n global $wpdb;\n\n $query = \"SELECT Row1, Row2 FROM table WHERE Row1 = '{$atts[text]}' ORDER BY Row1 ASC ;\";\n $results = $wpdb-&gt;get_results( $query, ARRAY_A );\n\n if( !empty( $results ) ){\n if( count( $results === 1 ) ){\n return $results[0];\n }else{\n return $results;\n } \n }else{\n return false;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 296371, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>Here's the SQL query:</p>\n\n<pre><code> $simplelist = $wpdb-&gt;get_results(\"SELECT `Row1`, `Row2` \n FROM `table` \n WHERE `Row1` = \" . $atts[text] . \"\n ORDER BY `Row1` ASC\");\n</code></pre>\n\n<p>Lets pretend we're the computer and run it in our heads, and the first thing that happens is:</p>\n\n<pre><code>$atts[text] // fatal error!\n</code></pre>\n\n<p><code>text</code> isn't defined, you're missing quotes, but lets fix that and we run into a new issue. If this value is <code>test</code> the result is:</p>\n\n<pre><code> SELECT `Row1`, `Row2` \n FROM `table` \n WHERE `Row1` = test\n ORDER BY `Row1` ASC\n</code></pre>\n\n<p><code>test</code> is missing quotes, which is why your query doesn't work.</p>\n\n<h2>The Massive Security Hole</h2>\n\n<p>Well you might be thinking <em>\"But Tom! Lets just surround it in quotes and it'll be all fine!\"</em>, but we have a problem. There's no preparing of the statement, so all we need to do is break out of the quotes and insert arbitrary SQL statements. Now anywhere that renders shortcodes can be used to dump any table, drop tables, modify data, and so on.</p>\n\n<p>To fix this, and prevent the original problem, use wpdb prepare, e.g.:</p>\n\n<pre><code>$table_name = \"wp_myTable\";\n$myID = 12;\n\n$wpdb-&gt;query( $wpdb-&gt;prepare( \"UPDATE `$table_name` SET `your_column_1` = 1 WHERE `$table_name`.`your_column_id` = %d\", $myID ) );\n</code></pre>\n\n<p><code>prepare</code> will make sure the value is safely inserted into the query string in the correct format with the right data type.</p>\n\n<p>Or you can just use a custom post type and avoid all the pain, with the free archives/URLs/templates/UIs/caching/REST endpoints/etc</p>\n" } ]
2018/03/09
[ "https://wordpress.stackexchange.com/questions/296366", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138252/" ]
I have created a small shortcode function with attributes to review if attributes are handled properly. That's the case and now I would like to use the attribute in a SELECT statement. But the database does not provide any values. The SQL statement without variable in the WHERE condition is okay. To test shortcodes, I've added this three lines into my Wordpress text page, but nor of them is working: ``` [simplelist text=Beatles] [simplelist text='Beatles'] [simplelist text="Beatles"] ``` And here is my code from functions.php: ``` <?php .... function get_list( $atts ) { $atts = shortcode_atts( array( 'text' => '', ), $atts); global $wpdb; $simplelist = $wpdb->get_results("SELECT `Row1`, `Row2` FROM `table` WHERE `Row1` = " . $atts[text] . " ORDER BY `Row1` ASC"); $Result = .... some stuff here ... return $Result; } add_shortcode('simplelist', 'get_list' ); ?> ``` When I remove the WHERE condition, I get complete table results. I need some help in using attribute values in WHERE condition.
Here's the SQL query: ``` $simplelist = $wpdb->get_results("SELECT `Row1`, `Row2` FROM `table` WHERE `Row1` = " . $atts[text] . " ORDER BY `Row1` ASC"); ``` Lets pretend we're the computer and run it in our heads, and the first thing that happens is: ``` $atts[text] // fatal error! ``` `text` isn't defined, you're missing quotes, but lets fix that and we run into a new issue. If this value is `test` the result is: ``` SELECT `Row1`, `Row2` FROM `table` WHERE `Row1` = test ORDER BY `Row1` ASC ``` `test` is missing quotes, which is why your query doesn't work. The Massive Security Hole ------------------------- Well you might be thinking *"But Tom! Lets just surround it in quotes and it'll be all fine!"*, but we have a problem. There's no preparing of the statement, so all we need to do is break out of the quotes and insert arbitrary SQL statements. Now anywhere that renders shortcodes can be used to dump any table, drop tables, modify data, and so on. To fix this, and prevent the original problem, use wpdb prepare, e.g.: ``` $table_name = "wp_myTable"; $myID = 12; $wpdb->query( $wpdb->prepare( "UPDATE `$table_name` SET `your_column_1` = 1 WHERE `$table_name`.`your_column_id` = %d", $myID ) ); ``` `prepare` will make sure the value is safely inserted into the query string in the correct format with the right data type. Or you can just use a custom post type and avoid all the pain, with the free archives/URLs/templates/UIs/caching/REST endpoints/etc
296,416
<p>I have two hooks in separate HTML request.</p> <p>I have to pass some data i.e. variable from one to the other.</p> <p>What is the most practical and transparent method for it?</p>
[ { "answer_id": 296418, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>It's not possible to pass data from one HTTP request to another one on the fly. Once the script is finished, the data will be discarded.</p>\n\n<p>What you can do is to store the data in a transient, and then retrieve it later. Here's a simple example using <a href=\"https://codex.wordpress.org/Function_Reference/set_transient\" rel=\"nofollow noreferrer\"><code>set_transient()</code></a>:</p>\n\n<pre><code>set_transient( 'my_transient', $data, 1 * HOUR_IN_SECONDS );\n</code></pre>\n\n<p>Then, you can retrieve it using <a href=\"https://codex.wordpress.org/Function_Reference/get_transient\" rel=\"nofollow noreferrer\"><code>get_transient()</code></a>:</p>\n\n<pre><code>get_transient( 'my_transient' );\n</code></pre>\n" }, { "answer_id": 296431, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>in the very general case, you just can not. Two http requests are fully independent from each other, and in case of big site might not even be processed by the same server.</p>\n\n<p>What you need to do is to \"force\" the second request to carry information that will help you identify or extract the relevant values when processing it.</p>\n\n<p>The most basic mechanism for that is cookies, but that is not the only one, and if for example you handle multi page form, you can simply include it as hidden input in the next form page you generate, and if the whole thing is done via AJAX, you can add state information in a reply to the first request, store it in some global space, and attach it to the next request.</p>\n" } ]
2018/03/11
[ "https://wordpress.stackexchange.com/questions/296416", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137445/" ]
I have two hooks in separate HTML request. I have to pass some data i.e. variable from one to the other. What is the most practical and transparent method for it?
It's not possible to pass data from one HTTP request to another one on the fly. Once the script is finished, the data will be discarded. What you can do is to store the data in a transient, and then retrieve it later. Here's a simple example using [`set_transient()`](https://codex.wordpress.org/Function_Reference/set_transient): ``` set_transient( 'my_transient', $data, 1 * HOUR_IN_SECONDS ); ``` Then, you can retrieve it using [`get_transient()`](https://codex.wordpress.org/Function_Reference/get_transient): ``` get_transient( 'my_transient' ); ```