qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
sequence
input
stringlengths
12
45k
output
stringlengths
2
31.8k
357,540
<p>I have this loop:</p> <pre><code>&lt;?php $categories = get_terms('my_category'); foreach ( $categories as $category ) : ?&gt; </code></pre> <p>I want to split the posts into 4 separate div columns so that post titles will be alphabetical vertically like:</p> <pre> a | d | g | j b | e | h | k c | f | i | l </pre> <p>How do you get the total post count and divide evenly into fourths?</p> <p>Edit: Here is the whole loop I'm working with</p> <pre><code>&lt;?php $categories = get_terms('archive_category'); foreach ( $categories as $category ) : ?&gt; &lt;div&gt; &lt;a data-toggle="collapse" href="#&lt;?php echo $category-&gt;slug; ?&gt;"&gt;&lt;h3&gt;&lt;?php echo $count; ?&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/h3&gt;&lt;/a&gt; &lt;div class="collapse" id="&lt;?php echo $category-&gt;slug; ?&gt;"&gt; &lt;?php $posts = get_posts(array( 'post_type' =&gt; array('custom_post', 'custom_post', 'custom_post'), 'taxonomy' =&gt; $category-&gt;taxonomy, 'term' =&gt; $category-&gt;slug, 'numberposts' =&gt; -1, 'orderby'=&gt;'title', 'order'=&gt;'ASC' )); foreach($posts as $post) : setup_postdata($post); ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php echo get_the_title( $p-&gt;ID ); ?&gt;&lt;/a&gt; &lt;?php endforeach; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endforeach; ?&gt; </code></pre>
[ { "answer_id": 357544, "author": "Waldo Rabie", "author_id": 172667, "author_profile": "https://wordpress.stackexchange.com/users/172667", "pm_score": 0, "selected": false, "text": "<p>The answer is CSS and you've got a couple options! </p>\n\n<pre><code>&lt;?php $categories = get_terms('my_category'); ?&gt;\n\n&lt;ul&gt;\n &lt;?php foreach ( $categories as $index =&gt; $category ): ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php echo get_the_title( $p-&gt;ID ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>You can use Flexbox...</p>\n\n<pre><code>ul {\n display: flex;\n flex-direction: column;\n flex-wrap: wrap;\n height: 306px;\n width: 200px;\n}\nli {\n width: 100px;\n height: 100px;\n}\n</code></pre>\n\n<p>OR, you can use Text Columns</p>\n\n<pre><code>ul {\n column-count: 2;\n column-gap: 0;\n}\nli {\n display: inline-block;\n}\n</code></pre>\n\n<p><a href=\"https://css-tricks.com/arranging-elements-top-bottom-instead-left-right-float/\" rel=\"nofollow noreferrer\">Here's</a> a great resource with further details and codepens.</p>\n" }, { "answer_id": 357591, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": true, "text": "<p>I had a similar problem couple years ago. Here's a gist I've published, which shows the basic idea how I solved the problem,<a href=\"https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d\" rel=\"nofollow noreferrer\">https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d</a></p>\n\n<p>Applying the gist to your situation I think the solution could be something like this. I didn't test this so it might require some tweaking, but it should at least point you to the right direction. Of course you need to add relevant css for the <code>ul</code> elements to position them next to each other.</p>\n\n<p>In my example I moved the term and post queries to their own helper functions, but this is just a matter of preference.</p>\n\n<pre><code>function archive_categories( string $tax ) {\n $categories = get_terms($tax);\n return ( $categories &amp;&amp; is_array($categories) ) ? $categories: array();\n}\n\nfunction archive_category_posts_query( string $tax, string $term ) {\n $args = array(\n 'post_type' =&gt; array('custom_post', 'custom_post', 'custom_post'),\n 'numberposts' =&gt; -1,\n 'orderby' =&gt; 'title',\n 'order' =&gt; 'ASC'\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; $tax,\n 'field' =&gt; 'slug',\n 'terms' =&gt; $term,\n ),\n ),\n );\n return new WP_Query($args);\n}\n\n$categories = archive_categories('archive_category');\n$col_count = 4;\n\nforeach ($categories as $category) :\n $category_posts_query = archive_category_posts_query($category-&gt;taxonomy, $category-&gt;slug);\n $post_count = $category_posts_query-&gt;found_posts;\n $posts_per_col = ceil( $post_count / $col_count );\n $i = 0;\n ?&gt;\n &lt;div&gt;\n &lt;a data-toggle=\"collapse\" href=\"#&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;h3&gt;&lt;?php echo $count; ?&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/h3&gt;\n &lt;/a&gt;\n &lt;div class=\"collapse\" id=\"&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;ul&gt;\n &lt;?php foreach ( $category_posts_query-&gt;posts as $category_post ) : \n if ( $posts_per_col === $i ) {\n $i = 0; \n echo '&lt;/ul&gt;&lt;ul&gt;';\n }\n ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php esc_url( get_the_permalink( $category_post-&gt;ID ) ); ?&gt;\"&gt;&lt;?php echo esc_html( $category_post-&gt;post_title ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php $i++; endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt; &lt;!-- collapse --&gt;\n &lt;/div&gt; &lt;!-- collapse wrapper --&gt;\n&lt;?php endforeach;\n</code></pre>\n\n<p><strong>EDIT 5.2.2020</strong></p>\n\n<p>Categories into columns? You mean something like this?</p>\n\n<pre><code>$categories = archive_categories('archive_category');\n$category_count = count( $categories );\n$col_count = 3;\n$categories_per_col = $category_count &gt; $col_count ? ceil( $category_count / $col_count ) : 1;\n$column_index = 1;\n\necho '&lt;div class=\"row\"&gt;';\nforeach ($categories as $category) :\n $category_posts_query = archive_category_posts_query($category-&gt;taxonomy, $category-&gt;slug);\n if ( $column_index &gt; $col_count ) {\n $column_index = 1;\n echo '&lt;/div&gt;&lt;div class=\"row\"&gt;';\n }\n $classes = array(\n 'column_1_of_' . $col_count,\n 'column-' . $column_index,\n );\n ?&gt;\n &lt;div class=\"&lt;?php echo implode( ' ', $classes ); ?&gt;\"&gt;\n &lt;a data-toggle=\"collapse\" href=\"#&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;h3&gt;&lt;?php echo $category-&gt;count . ' ' . $category-&gt;name; ?&gt;&lt;/h3&gt;\n &lt;/a&gt;\n &lt;div class=\"collapse\" id=\"&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;ul&gt;\n &lt;?php foreach ( $category_posts_query-&gt;posts as $category_post ) : ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php esc_url( get_the_permalink( $category_post-&gt;ID ) ); ?&gt;\"&gt;&lt;?php echo esc_html( $category_post-&gt;post_title ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt; &lt;!-- collapse --&gt;\n &lt;/div&gt; &lt;!-- collapse wrapper --&gt;\n&lt;?php $column_index++; endforeach;\necho '&lt;/div&gt;';\n</code></pre>\n" } ]
2020/01/30
[ "https://wordpress.stackexchange.com/questions/357540", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28232/" ]
I have this loop: ``` <?php $categories = get_terms('my_category'); foreach ( $categories as $category ) : ?> ``` I want to split the posts into 4 separate div columns so that post titles will be alphabetical vertically like: ``` a | d | g | j b | e | h | k c | f | i | l ``` How do you get the total post count and divide evenly into fourths? Edit: Here is the whole loop I'm working with ``` <?php $categories = get_terms('archive_category'); foreach ( $categories as $category ) : ?> <div> <a data-toggle="collapse" href="#<?php echo $category->slug; ?>"><h3><?php echo $count; ?><?php echo $category->name; ?></h3></a> <div class="collapse" id="<?php echo $category->slug; ?>"> <?php $posts = get_posts(array( 'post_type' => array('custom_post', 'custom_post', 'custom_post'), 'taxonomy' => $category->taxonomy, 'term' => $category->slug, 'numberposts' => -1, 'orderby'=>'title', 'order'=>'ASC' )); foreach($posts as $post) : setup_postdata($post); ?> <a href="<?php the_permalink(); ?>"><?php echo get_the_title( $p->ID ); ?></a> <?php endforeach; ?> </div> </div> <?php endforeach; ?> ```
I had a similar problem couple years ago. Here's a gist I've published, which shows the basic idea how I solved the problem,<https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d> Applying the gist to your situation I think the solution could be something like this. I didn't test this so it might require some tweaking, but it should at least point you to the right direction. Of course you need to add relevant css for the `ul` elements to position them next to each other. In my example I moved the term and post queries to their own helper functions, but this is just a matter of preference. ``` function archive_categories( string $tax ) { $categories = get_terms($tax); return ( $categories && is_array($categories) ) ? $categories: array(); } function archive_category_posts_query( string $tax, string $term ) { $args = array( 'post_type' => array('custom_post', 'custom_post', 'custom_post'), 'numberposts' => -1, 'orderby' => 'title', 'order' => 'ASC' 'tax_query' => array( array( 'taxonomy' => $tax, 'field' => 'slug', 'terms' => $term, ), ), ); return new WP_Query($args); } $categories = archive_categories('archive_category'); $col_count = 4; foreach ($categories as $category) : $category_posts_query = archive_category_posts_query($category->taxonomy, $category->slug); $post_count = $category_posts_query->found_posts; $posts_per_col = ceil( $post_count / $col_count ); $i = 0; ?> <div> <a data-toggle="collapse" href="#<?php echo $category->slug; ?>"> <h3><?php echo $count; ?><?php echo $category->name; ?></h3> </a> <div class="collapse" id="<?php echo $category->slug; ?>"> <ul> <?php foreach ( $category_posts_query->posts as $category_post ) : if ( $posts_per_col === $i ) { $i = 0; echo '</ul><ul>'; } ?> <li> <a href="<?php esc_url( get_the_permalink( $category_post->ID ) ); ?>"><?php echo esc_html( $category_post->post_title ); ?></a> </li> <?php $i++; endforeach; ?> </ul> </div> <!-- collapse --> </div> <!-- collapse wrapper --> <?php endforeach; ``` **EDIT 5.2.2020** Categories into columns? You mean something like this? ``` $categories = archive_categories('archive_category'); $category_count = count( $categories ); $col_count = 3; $categories_per_col = $category_count > $col_count ? ceil( $category_count / $col_count ) : 1; $column_index = 1; echo '<div class="row">'; foreach ($categories as $category) : $category_posts_query = archive_category_posts_query($category->taxonomy, $category->slug); if ( $column_index > $col_count ) { $column_index = 1; echo '</div><div class="row">'; } $classes = array( 'column_1_of_' . $col_count, 'column-' . $column_index, ); ?> <div class="<?php echo implode( ' ', $classes ); ?>"> <a data-toggle="collapse" href="#<?php echo $category->slug; ?>"> <h3><?php echo $category->count . ' ' . $category->name; ?></h3> </a> <div class="collapse" id="<?php echo $category->slug; ?>"> <ul> <?php foreach ( $category_posts_query->posts as $category_post ) : ?> <li> <a href="<?php esc_url( get_the_permalink( $category_post->ID ) ); ?>"><?php echo esc_html( $category_post->post_title ); ?></a> </li> <?php endforeach; ?> </ul> </div> <!-- collapse --> </div> <!-- collapse wrapper --> <?php $column_index++; endforeach; echo '</div>'; ```
357,650
<p>I'm trying to override the number of posts to show on pagination for my search.php template, to be 16 vs 4. In the Reading settings on the back end, it is set to 4, which is desired because my front page uses the same code to display the 4 most recent posts.</p> <p>Is there a way to designate this on the search.php template page?</p> <p>This is my template page for Search.php</p> <pre><code>&lt;?php get_header(); global $wp_query; ?&gt; &lt;picture class="featured-image block pos-rel"&gt; &lt;div class="t-con flex row pos-abs"&gt; &lt;h1 class="post-title f-center" title="&lt;?php echo $wp_query-&gt;found_posts; ?&gt; &lt;?php _e( 'Search Results Found For', 'locale' ); ?&gt;: &lt;?php the_search_query(); ?&gt;"&gt;&lt;?php echo $wp_query-&gt;found_posts; ?&gt; &lt;?php _e( 'Search Results Found For', 'locale' ); ?&gt;: "&lt;?php the_search_query(); ?&gt;"&lt;/h1&gt; &lt;!--Edit these values to adjust page being shown.--&gt; &lt;/div&gt; &lt;?php echo get_the_post_thumbnail($page=2, 'full', array( 'class' =&gt; 'featured' )); ?&gt; &lt;/picture&gt; &lt;section class="main bg-darkpurple"&gt; &lt;div&gt; &lt;div class="grid row posts"&gt; &lt;?php while ( have_posts() ) : the_post(); ?&gt; &lt;div class="col"&gt; &lt;div class="date-container"&gt; &lt;p class="post-date bg-darkpurple"&gt; &lt;?php $u_time = get_the_time('U'); $u_modified_time = get_the_modified_time('U'); if ($u_modified_time &gt;= $u_time + 86400) { echo "Last updated "; the_modified_time('F jS, Y'); echo ""; } else {echo "Posted "; the_time('F jS, Y');} ?&gt; &lt;/p&gt; &lt;/div&gt; &lt;?php $primary_cat = get_post_meta($post-&gt;ID , '_category_permalink', true); if ( $primary_cat != null ) { $cat_id = $primary_cat['category']; $category = get_category($cat_id); } else { $categories = get_the_category(); $category = $categories[0]; } $category_link = get_category_link($category); $category_name = $category-&gt;name; ?&gt; &lt;picture class="post-thumb block"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_post_thumbnail('medium'); ?&gt;&lt;/a&gt; &lt;div class="cat-container"&gt; &lt;a class="post-cat bg-darkpurple" href="&lt;?php echo $category_link ?&gt;"&gt;&lt;?php echo $category_name ?&gt;&lt;/a&gt; &lt;/div&gt; &lt;/picture&gt; &lt;h3&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;?php the_title(); ?&gt; &lt;/a&gt; &lt;/h3&gt; &lt;p&gt;&lt;?php echo substr(get_the_excerpt(), 0,160); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt; &lt;div class="pagination flex row f-center"&gt; &lt;?php echo paginate_links( array( 'end_size' =&gt; 2, 'mid_size' =&gt; 1, 'prev_text' =&gt; sprintf( '&lt;i&gt;&lt;/i&gt; %1$s', __( 'Other results', 'text-domain' ) ), 'next_text' =&gt; sprintf( '%1$s &lt;i&gt;&lt;/i&gt;', __( 'Other results', 'text-domain' ) ), ) ); ?&gt; &lt;/div&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;/div&gt; &lt;/section&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>I know this line of code should be what I need, but I'm not sure WHERE to put it:</p> <pre><code>'posts_per_page' =&gt; 16 </code></pre> <p>Thanks for any help!</p>
[ { "answer_id": 357544, "author": "Waldo Rabie", "author_id": 172667, "author_profile": "https://wordpress.stackexchange.com/users/172667", "pm_score": 0, "selected": false, "text": "<p>The answer is CSS and you've got a couple options! </p>\n\n<pre><code>&lt;?php $categories = get_terms('my_category'); ?&gt;\n\n&lt;ul&gt;\n &lt;?php foreach ( $categories as $index =&gt; $category ): ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php echo get_the_title( $p-&gt;ID ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>You can use Flexbox...</p>\n\n<pre><code>ul {\n display: flex;\n flex-direction: column;\n flex-wrap: wrap;\n height: 306px;\n width: 200px;\n}\nli {\n width: 100px;\n height: 100px;\n}\n</code></pre>\n\n<p>OR, you can use Text Columns</p>\n\n<pre><code>ul {\n column-count: 2;\n column-gap: 0;\n}\nli {\n display: inline-block;\n}\n</code></pre>\n\n<p><a href=\"https://css-tricks.com/arranging-elements-top-bottom-instead-left-right-float/\" rel=\"nofollow noreferrer\">Here's</a> a great resource with further details and codepens.</p>\n" }, { "answer_id": 357591, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": true, "text": "<p>I had a similar problem couple years ago. Here's a gist I've published, which shows the basic idea how I solved the problem,<a href=\"https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d\" rel=\"nofollow noreferrer\">https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d</a></p>\n\n<p>Applying the gist to your situation I think the solution could be something like this. I didn't test this so it might require some tweaking, but it should at least point you to the right direction. Of course you need to add relevant css for the <code>ul</code> elements to position them next to each other.</p>\n\n<p>In my example I moved the term and post queries to their own helper functions, but this is just a matter of preference.</p>\n\n<pre><code>function archive_categories( string $tax ) {\n $categories = get_terms($tax);\n return ( $categories &amp;&amp; is_array($categories) ) ? $categories: array();\n}\n\nfunction archive_category_posts_query( string $tax, string $term ) {\n $args = array(\n 'post_type' =&gt; array('custom_post', 'custom_post', 'custom_post'),\n 'numberposts' =&gt; -1,\n 'orderby' =&gt; 'title',\n 'order' =&gt; 'ASC'\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; $tax,\n 'field' =&gt; 'slug',\n 'terms' =&gt; $term,\n ),\n ),\n );\n return new WP_Query($args);\n}\n\n$categories = archive_categories('archive_category');\n$col_count = 4;\n\nforeach ($categories as $category) :\n $category_posts_query = archive_category_posts_query($category-&gt;taxonomy, $category-&gt;slug);\n $post_count = $category_posts_query-&gt;found_posts;\n $posts_per_col = ceil( $post_count / $col_count );\n $i = 0;\n ?&gt;\n &lt;div&gt;\n &lt;a data-toggle=\"collapse\" href=\"#&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;h3&gt;&lt;?php echo $count; ?&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/h3&gt;\n &lt;/a&gt;\n &lt;div class=\"collapse\" id=\"&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;ul&gt;\n &lt;?php foreach ( $category_posts_query-&gt;posts as $category_post ) : \n if ( $posts_per_col === $i ) {\n $i = 0; \n echo '&lt;/ul&gt;&lt;ul&gt;';\n }\n ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php esc_url( get_the_permalink( $category_post-&gt;ID ) ); ?&gt;\"&gt;&lt;?php echo esc_html( $category_post-&gt;post_title ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php $i++; endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt; &lt;!-- collapse --&gt;\n &lt;/div&gt; &lt;!-- collapse wrapper --&gt;\n&lt;?php endforeach;\n</code></pre>\n\n<p><strong>EDIT 5.2.2020</strong></p>\n\n<p>Categories into columns? You mean something like this?</p>\n\n<pre><code>$categories = archive_categories('archive_category');\n$category_count = count( $categories );\n$col_count = 3;\n$categories_per_col = $category_count &gt; $col_count ? ceil( $category_count / $col_count ) : 1;\n$column_index = 1;\n\necho '&lt;div class=\"row\"&gt;';\nforeach ($categories as $category) :\n $category_posts_query = archive_category_posts_query($category-&gt;taxonomy, $category-&gt;slug);\n if ( $column_index &gt; $col_count ) {\n $column_index = 1;\n echo '&lt;/div&gt;&lt;div class=\"row\"&gt;';\n }\n $classes = array(\n 'column_1_of_' . $col_count,\n 'column-' . $column_index,\n );\n ?&gt;\n &lt;div class=\"&lt;?php echo implode( ' ', $classes ); ?&gt;\"&gt;\n &lt;a data-toggle=\"collapse\" href=\"#&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;h3&gt;&lt;?php echo $category-&gt;count . ' ' . $category-&gt;name; ?&gt;&lt;/h3&gt;\n &lt;/a&gt;\n &lt;div class=\"collapse\" id=\"&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;ul&gt;\n &lt;?php foreach ( $category_posts_query-&gt;posts as $category_post ) : ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php esc_url( get_the_permalink( $category_post-&gt;ID ) ); ?&gt;\"&gt;&lt;?php echo esc_html( $category_post-&gt;post_title ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt; &lt;!-- collapse --&gt;\n &lt;/div&gt; &lt;!-- collapse wrapper --&gt;\n&lt;?php $column_index++; endforeach;\necho '&lt;/div&gt;';\n</code></pre>\n" } ]
2020/01/31
[ "https://wordpress.stackexchange.com/questions/357650", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/181216/" ]
I'm trying to override the number of posts to show on pagination for my search.php template, to be 16 vs 4. In the Reading settings on the back end, it is set to 4, which is desired because my front page uses the same code to display the 4 most recent posts. Is there a way to designate this on the search.php template page? This is my template page for Search.php ``` <?php get_header(); global $wp_query; ?> <picture class="featured-image block pos-rel"> <div class="t-con flex row pos-abs"> <h1 class="post-title f-center" title="<?php echo $wp_query->found_posts; ?> <?php _e( 'Search Results Found For', 'locale' ); ?>: <?php the_search_query(); ?>"><?php echo $wp_query->found_posts; ?> <?php _e( 'Search Results Found For', 'locale' ); ?>: "<?php the_search_query(); ?>"</h1> <!--Edit these values to adjust page being shown.--> </div> <?php echo get_the_post_thumbnail($page=2, 'full', array( 'class' => 'featured' )); ?> </picture> <section class="main bg-darkpurple"> <div> <div class="grid row posts"> <?php while ( have_posts() ) : the_post(); ?> <div class="col"> <div class="date-container"> <p class="post-date bg-darkpurple"> <?php $u_time = get_the_time('U'); $u_modified_time = get_the_modified_time('U'); if ($u_modified_time >= $u_time + 86400) { echo "Last updated "; the_modified_time('F jS, Y'); echo ""; } else {echo "Posted "; the_time('F jS, Y');} ?> </p> </div> <?php $primary_cat = get_post_meta($post->ID , '_category_permalink', true); if ( $primary_cat != null ) { $cat_id = $primary_cat['category']; $category = get_category($cat_id); } else { $categories = get_the_category(); $category = $categories[0]; } $category_link = get_category_link($category); $category_name = $category->name; ?> <picture class="post-thumb block"> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('medium'); ?></a> <div class="cat-container"> <a class="post-cat bg-darkpurple" href="<?php echo $category_link ?>"><?php echo $category_name ?></a> </div> </picture> <h3> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a> </h3> <p><?php echo substr(get_the_excerpt(), 0,160); ?></p> </div> <?php endwhile; ?> </div> <div class="pagination flex row f-center"> <?php echo paginate_links( array( 'end_size' => 2, 'mid_size' => 1, 'prev_text' => sprintf( '<i></i> %1$s', __( 'Other results', 'text-domain' ) ), 'next_text' => sprintf( '%1$s <i></i>', __( 'Other results', 'text-domain' ) ), ) ); ?> </div> <?php wp_reset_postdata(); ?> </div> </section> <?php get_footer(); ?> ``` I know this line of code should be what I need, but I'm not sure WHERE to put it: ``` 'posts_per_page' => 16 ``` Thanks for any help!
I had a similar problem couple years ago. Here's a gist I've published, which shows the basic idea how I solved the problem,<https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d> Applying the gist to your situation I think the solution could be something like this. I didn't test this so it might require some tweaking, but it should at least point you to the right direction. Of course you need to add relevant css for the `ul` elements to position them next to each other. In my example I moved the term and post queries to their own helper functions, but this is just a matter of preference. ``` function archive_categories( string $tax ) { $categories = get_terms($tax); return ( $categories && is_array($categories) ) ? $categories: array(); } function archive_category_posts_query( string $tax, string $term ) { $args = array( 'post_type' => array('custom_post', 'custom_post', 'custom_post'), 'numberposts' => -1, 'orderby' => 'title', 'order' => 'ASC' 'tax_query' => array( array( 'taxonomy' => $tax, 'field' => 'slug', 'terms' => $term, ), ), ); return new WP_Query($args); } $categories = archive_categories('archive_category'); $col_count = 4; foreach ($categories as $category) : $category_posts_query = archive_category_posts_query($category->taxonomy, $category->slug); $post_count = $category_posts_query->found_posts; $posts_per_col = ceil( $post_count / $col_count ); $i = 0; ?> <div> <a data-toggle="collapse" href="#<?php echo $category->slug; ?>"> <h3><?php echo $count; ?><?php echo $category->name; ?></h3> </a> <div class="collapse" id="<?php echo $category->slug; ?>"> <ul> <?php foreach ( $category_posts_query->posts as $category_post ) : if ( $posts_per_col === $i ) { $i = 0; echo '</ul><ul>'; } ?> <li> <a href="<?php esc_url( get_the_permalink( $category_post->ID ) ); ?>"><?php echo esc_html( $category_post->post_title ); ?></a> </li> <?php $i++; endforeach; ?> </ul> </div> <!-- collapse --> </div> <!-- collapse wrapper --> <?php endforeach; ``` **EDIT 5.2.2020** Categories into columns? You mean something like this? ``` $categories = archive_categories('archive_category'); $category_count = count( $categories ); $col_count = 3; $categories_per_col = $category_count > $col_count ? ceil( $category_count / $col_count ) : 1; $column_index = 1; echo '<div class="row">'; foreach ($categories as $category) : $category_posts_query = archive_category_posts_query($category->taxonomy, $category->slug); if ( $column_index > $col_count ) { $column_index = 1; echo '</div><div class="row">'; } $classes = array( 'column_1_of_' . $col_count, 'column-' . $column_index, ); ?> <div class="<?php echo implode( ' ', $classes ); ?>"> <a data-toggle="collapse" href="#<?php echo $category->slug; ?>"> <h3><?php echo $category->count . ' ' . $category->name; ?></h3> </a> <div class="collapse" id="<?php echo $category->slug; ?>"> <ul> <?php foreach ( $category_posts_query->posts as $category_post ) : ?> <li> <a href="<?php esc_url( get_the_permalink( $category_post->ID ) ); ?>"><?php echo esc_html( $category_post->post_title ); ?></a> </li> <?php endforeach; ?> </ul> </div> <!-- collapse --> </div> <!-- collapse wrapper --> <?php $column_index++; endforeach; echo '</div>'; ```
357,710
<p>One of my websites scan by a security firm and came up with below to block "<a href="http://domain.com/wp-includes/sodium_compat/composer.json" rel="nofollow noreferrer">http://domain.com/wp-includes/sodium_compat/composer.json</a>" access over the internet. I've tried few plugins but none of them work, does anyone know how to block similar files display JSON on the browser.</p>
[ { "answer_id": 357544, "author": "Waldo Rabie", "author_id": 172667, "author_profile": "https://wordpress.stackexchange.com/users/172667", "pm_score": 0, "selected": false, "text": "<p>The answer is CSS and you've got a couple options! </p>\n\n<pre><code>&lt;?php $categories = get_terms('my_category'); ?&gt;\n\n&lt;ul&gt;\n &lt;?php foreach ( $categories as $index =&gt; $category ): ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php echo get_the_title( $p-&gt;ID ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>You can use Flexbox...</p>\n\n<pre><code>ul {\n display: flex;\n flex-direction: column;\n flex-wrap: wrap;\n height: 306px;\n width: 200px;\n}\nli {\n width: 100px;\n height: 100px;\n}\n</code></pre>\n\n<p>OR, you can use Text Columns</p>\n\n<pre><code>ul {\n column-count: 2;\n column-gap: 0;\n}\nli {\n display: inline-block;\n}\n</code></pre>\n\n<p><a href=\"https://css-tricks.com/arranging-elements-top-bottom-instead-left-right-float/\" rel=\"nofollow noreferrer\">Here's</a> a great resource with further details and codepens.</p>\n" }, { "answer_id": 357591, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": true, "text": "<p>I had a similar problem couple years ago. Here's a gist I've published, which shows the basic idea how I solved the problem,<a href=\"https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d\" rel=\"nofollow noreferrer\">https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d</a></p>\n\n<p>Applying the gist to your situation I think the solution could be something like this. I didn't test this so it might require some tweaking, but it should at least point you to the right direction. Of course you need to add relevant css for the <code>ul</code> elements to position them next to each other.</p>\n\n<p>In my example I moved the term and post queries to their own helper functions, but this is just a matter of preference.</p>\n\n<pre><code>function archive_categories( string $tax ) {\n $categories = get_terms($tax);\n return ( $categories &amp;&amp; is_array($categories) ) ? $categories: array();\n}\n\nfunction archive_category_posts_query( string $tax, string $term ) {\n $args = array(\n 'post_type' =&gt; array('custom_post', 'custom_post', 'custom_post'),\n 'numberposts' =&gt; -1,\n 'orderby' =&gt; 'title',\n 'order' =&gt; 'ASC'\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; $tax,\n 'field' =&gt; 'slug',\n 'terms' =&gt; $term,\n ),\n ),\n );\n return new WP_Query($args);\n}\n\n$categories = archive_categories('archive_category');\n$col_count = 4;\n\nforeach ($categories as $category) :\n $category_posts_query = archive_category_posts_query($category-&gt;taxonomy, $category-&gt;slug);\n $post_count = $category_posts_query-&gt;found_posts;\n $posts_per_col = ceil( $post_count / $col_count );\n $i = 0;\n ?&gt;\n &lt;div&gt;\n &lt;a data-toggle=\"collapse\" href=\"#&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;h3&gt;&lt;?php echo $count; ?&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/h3&gt;\n &lt;/a&gt;\n &lt;div class=\"collapse\" id=\"&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;ul&gt;\n &lt;?php foreach ( $category_posts_query-&gt;posts as $category_post ) : \n if ( $posts_per_col === $i ) {\n $i = 0; \n echo '&lt;/ul&gt;&lt;ul&gt;';\n }\n ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php esc_url( get_the_permalink( $category_post-&gt;ID ) ); ?&gt;\"&gt;&lt;?php echo esc_html( $category_post-&gt;post_title ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php $i++; endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt; &lt;!-- collapse --&gt;\n &lt;/div&gt; &lt;!-- collapse wrapper --&gt;\n&lt;?php endforeach;\n</code></pre>\n\n<p><strong>EDIT 5.2.2020</strong></p>\n\n<p>Categories into columns? You mean something like this?</p>\n\n<pre><code>$categories = archive_categories('archive_category');\n$category_count = count( $categories );\n$col_count = 3;\n$categories_per_col = $category_count &gt; $col_count ? ceil( $category_count / $col_count ) : 1;\n$column_index = 1;\n\necho '&lt;div class=\"row\"&gt;';\nforeach ($categories as $category) :\n $category_posts_query = archive_category_posts_query($category-&gt;taxonomy, $category-&gt;slug);\n if ( $column_index &gt; $col_count ) {\n $column_index = 1;\n echo '&lt;/div&gt;&lt;div class=\"row\"&gt;';\n }\n $classes = array(\n 'column_1_of_' . $col_count,\n 'column-' . $column_index,\n );\n ?&gt;\n &lt;div class=\"&lt;?php echo implode( ' ', $classes ); ?&gt;\"&gt;\n &lt;a data-toggle=\"collapse\" href=\"#&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;h3&gt;&lt;?php echo $category-&gt;count . ' ' . $category-&gt;name; ?&gt;&lt;/h3&gt;\n &lt;/a&gt;\n &lt;div class=\"collapse\" id=\"&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;ul&gt;\n &lt;?php foreach ( $category_posts_query-&gt;posts as $category_post ) : ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php esc_url( get_the_permalink( $category_post-&gt;ID ) ); ?&gt;\"&gt;&lt;?php echo esc_html( $category_post-&gt;post_title ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt; &lt;!-- collapse --&gt;\n &lt;/div&gt; &lt;!-- collapse wrapper --&gt;\n&lt;?php $column_index++; endforeach;\necho '&lt;/div&gt;';\n</code></pre>\n" } ]
2020/02/02
[ "https://wordpress.stackexchange.com/questions/357710", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97402/" ]
One of my websites scan by a security firm and came up with below to block "<http://domain.com/wp-includes/sodium_compat/composer.json>" access over the internet. I've tried few plugins but none of them work, does anyone know how to block similar files display JSON on the browser.
I had a similar problem couple years ago. Here's a gist I've published, which shows the basic idea how I solved the problem,<https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d> Applying the gist to your situation I think the solution could be something like this. I didn't test this so it might require some tweaking, but it should at least point you to the right direction. Of course you need to add relevant css for the `ul` elements to position them next to each other. In my example I moved the term and post queries to their own helper functions, but this is just a matter of preference. ``` function archive_categories( string $tax ) { $categories = get_terms($tax); return ( $categories && is_array($categories) ) ? $categories: array(); } function archive_category_posts_query( string $tax, string $term ) { $args = array( 'post_type' => array('custom_post', 'custom_post', 'custom_post'), 'numberposts' => -1, 'orderby' => 'title', 'order' => 'ASC' 'tax_query' => array( array( 'taxonomy' => $tax, 'field' => 'slug', 'terms' => $term, ), ), ); return new WP_Query($args); } $categories = archive_categories('archive_category'); $col_count = 4; foreach ($categories as $category) : $category_posts_query = archive_category_posts_query($category->taxonomy, $category->slug); $post_count = $category_posts_query->found_posts; $posts_per_col = ceil( $post_count / $col_count ); $i = 0; ?> <div> <a data-toggle="collapse" href="#<?php echo $category->slug; ?>"> <h3><?php echo $count; ?><?php echo $category->name; ?></h3> </a> <div class="collapse" id="<?php echo $category->slug; ?>"> <ul> <?php foreach ( $category_posts_query->posts as $category_post ) : if ( $posts_per_col === $i ) { $i = 0; echo '</ul><ul>'; } ?> <li> <a href="<?php esc_url( get_the_permalink( $category_post->ID ) ); ?>"><?php echo esc_html( $category_post->post_title ); ?></a> </li> <?php $i++; endforeach; ?> </ul> </div> <!-- collapse --> </div> <!-- collapse wrapper --> <?php endforeach; ``` **EDIT 5.2.2020** Categories into columns? You mean something like this? ``` $categories = archive_categories('archive_category'); $category_count = count( $categories ); $col_count = 3; $categories_per_col = $category_count > $col_count ? ceil( $category_count / $col_count ) : 1; $column_index = 1; echo '<div class="row">'; foreach ($categories as $category) : $category_posts_query = archive_category_posts_query($category->taxonomy, $category->slug); if ( $column_index > $col_count ) { $column_index = 1; echo '</div><div class="row">'; } $classes = array( 'column_1_of_' . $col_count, 'column-' . $column_index, ); ?> <div class="<?php echo implode( ' ', $classes ); ?>"> <a data-toggle="collapse" href="#<?php echo $category->slug; ?>"> <h3><?php echo $category->count . ' ' . $category->name; ?></h3> </a> <div class="collapse" id="<?php echo $category->slug; ?>"> <ul> <?php foreach ( $category_posts_query->posts as $category_post ) : ?> <li> <a href="<?php esc_url( get_the_permalink( $category_post->ID ) ); ?>"><?php echo esc_html( $category_post->post_title ); ?></a> </li> <?php endforeach; ?> </ul> </div> <!-- collapse --> </div> <!-- collapse wrapper --> <?php $column_index++; endforeach; echo '</div>'; ```
357,733
<p>this seems hard to understand. I created a plugin, and it works fine on different installations of me and a few other blogs.</p> <p>But on one blog of someone else it fails. After getting through debugs and console entries, I believe I found the source of the failure:</p> <p>At some step of the process the plugin calls a function with ajax:</p> <pre><code>jQuery(document).ready(function($) { var data = { 'action': 'mp_throwcontent_2', 'MedioPay_postid': mp_mypostid, 'MedioPay_outputs': mp_outputs, 'MedioPay_number': mp_numberof_payments, 'MedioPay_userID': mp_userID, 'Mediopay_newCounter': mp_newCounter, 'MedioPay_firstPartner': mp_firstPartner, 'MedioPay_secondPartner': mp_secondPartner, 'MedioPay_thirdPartner': mp_thirdPartner, 'MedioPay_fourthPartner': mp_fourthPartner, 'MedioPay_shareQuote': mp_sharing, 'MedioPay_preview': mp_preview }; console.log("turning data over"); jQuery.post(my_ajax_object.ajax_url, data, function(response) { console.log("unlock 2 " + response); mp_unlockContent2(payment, response); }); }); </code></pre> <p>Then a function is called:</p> <pre><code>add_action ( 'wp_ajax_nopriv_mp_throwcontent_2', 'mp_throwcontent_2' ); function mp_throwcontent_2() { // some ifs and so on // echo "output" } </code></pre> <p>When the plugin starts, Ajax is localized</p> <pre><code>wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' =&gt; admin_url( 'admin-ajax.php' ) ) ); </code></pre> <p>A little quirk: I localized it twice, accidently, here too:</p> <pre><code>wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' =&gt; admin_url( 'admin-ajax.php' ), 'we_value' =&gt; 1234 ) ); </code></pre> <p>Can this be a problem?</p> <p>All this works very fine on a few blogs. But in one the operations just stop when the ajax starts. No error, nothing in debug, it just stops.</p> <p>Does anybody have an idea what I can do to make it run? Is there a fallback to call in case it fails?</p> <p>Ah, and to make it even weirder: The plugin worked fine on that blog, but suddenly it stopped working, while the owners tells me he didn't even change anything on his wordpress installation. </p>
[ { "answer_id": 357544, "author": "Waldo Rabie", "author_id": 172667, "author_profile": "https://wordpress.stackexchange.com/users/172667", "pm_score": 0, "selected": false, "text": "<p>The answer is CSS and you've got a couple options! </p>\n\n<pre><code>&lt;?php $categories = get_terms('my_category'); ?&gt;\n\n&lt;ul&gt;\n &lt;?php foreach ( $categories as $index =&gt; $category ): ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php echo get_the_title( $p-&gt;ID ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>You can use Flexbox...</p>\n\n<pre><code>ul {\n display: flex;\n flex-direction: column;\n flex-wrap: wrap;\n height: 306px;\n width: 200px;\n}\nli {\n width: 100px;\n height: 100px;\n}\n</code></pre>\n\n<p>OR, you can use Text Columns</p>\n\n<pre><code>ul {\n column-count: 2;\n column-gap: 0;\n}\nli {\n display: inline-block;\n}\n</code></pre>\n\n<p><a href=\"https://css-tricks.com/arranging-elements-top-bottom-instead-left-right-float/\" rel=\"nofollow noreferrer\">Here's</a> a great resource with further details and codepens.</p>\n" }, { "answer_id": 357591, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": true, "text": "<p>I had a similar problem couple years ago. Here's a gist I've published, which shows the basic idea how I solved the problem,<a href=\"https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d\" rel=\"nofollow noreferrer\">https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d</a></p>\n\n<p>Applying the gist to your situation I think the solution could be something like this. I didn't test this so it might require some tweaking, but it should at least point you to the right direction. Of course you need to add relevant css for the <code>ul</code> elements to position them next to each other.</p>\n\n<p>In my example I moved the term and post queries to their own helper functions, but this is just a matter of preference.</p>\n\n<pre><code>function archive_categories( string $tax ) {\n $categories = get_terms($tax);\n return ( $categories &amp;&amp; is_array($categories) ) ? $categories: array();\n}\n\nfunction archive_category_posts_query( string $tax, string $term ) {\n $args = array(\n 'post_type' =&gt; array('custom_post', 'custom_post', 'custom_post'),\n 'numberposts' =&gt; -1,\n 'orderby' =&gt; 'title',\n 'order' =&gt; 'ASC'\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; $tax,\n 'field' =&gt; 'slug',\n 'terms' =&gt; $term,\n ),\n ),\n );\n return new WP_Query($args);\n}\n\n$categories = archive_categories('archive_category');\n$col_count = 4;\n\nforeach ($categories as $category) :\n $category_posts_query = archive_category_posts_query($category-&gt;taxonomy, $category-&gt;slug);\n $post_count = $category_posts_query-&gt;found_posts;\n $posts_per_col = ceil( $post_count / $col_count );\n $i = 0;\n ?&gt;\n &lt;div&gt;\n &lt;a data-toggle=\"collapse\" href=\"#&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;h3&gt;&lt;?php echo $count; ?&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/h3&gt;\n &lt;/a&gt;\n &lt;div class=\"collapse\" id=\"&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;ul&gt;\n &lt;?php foreach ( $category_posts_query-&gt;posts as $category_post ) : \n if ( $posts_per_col === $i ) {\n $i = 0; \n echo '&lt;/ul&gt;&lt;ul&gt;';\n }\n ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php esc_url( get_the_permalink( $category_post-&gt;ID ) ); ?&gt;\"&gt;&lt;?php echo esc_html( $category_post-&gt;post_title ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php $i++; endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt; &lt;!-- collapse --&gt;\n &lt;/div&gt; &lt;!-- collapse wrapper --&gt;\n&lt;?php endforeach;\n</code></pre>\n\n<p><strong>EDIT 5.2.2020</strong></p>\n\n<p>Categories into columns? You mean something like this?</p>\n\n<pre><code>$categories = archive_categories('archive_category');\n$category_count = count( $categories );\n$col_count = 3;\n$categories_per_col = $category_count &gt; $col_count ? ceil( $category_count / $col_count ) : 1;\n$column_index = 1;\n\necho '&lt;div class=\"row\"&gt;';\nforeach ($categories as $category) :\n $category_posts_query = archive_category_posts_query($category-&gt;taxonomy, $category-&gt;slug);\n if ( $column_index &gt; $col_count ) {\n $column_index = 1;\n echo '&lt;/div&gt;&lt;div class=\"row\"&gt;';\n }\n $classes = array(\n 'column_1_of_' . $col_count,\n 'column-' . $column_index,\n );\n ?&gt;\n &lt;div class=\"&lt;?php echo implode( ' ', $classes ); ?&gt;\"&gt;\n &lt;a data-toggle=\"collapse\" href=\"#&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;h3&gt;&lt;?php echo $category-&gt;count . ' ' . $category-&gt;name; ?&gt;&lt;/h3&gt;\n &lt;/a&gt;\n &lt;div class=\"collapse\" id=\"&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;ul&gt;\n &lt;?php foreach ( $category_posts_query-&gt;posts as $category_post ) : ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php esc_url( get_the_permalink( $category_post-&gt;ID ) ); ?&gt;\"&gt;&lt;?php echo esc_html( $category_post-&gt;post_title ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt; &lt;!-- collapse --&gt;\n &lt;/div&gt; &lt;!-- collapse wrapper --&gt;\n&lt;?php $column_index++; endforeach;\necho '&lt;/div&gt;';\n</code></pre>\n" } ]
2020/02/02
[ "https://wordpress.stackexchange.com/questions/357733", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176007/" ]
this seems hard to understand. I created a plugin, and it works fine on different installations of me and a few other blogs. But on one blog of someone else it fails. After getting through debugs and console entries, I believe I found the source of the failure: At some step of the process the plugin calls a function with ajax: ``` jQuery(document).ready(function($) { var data = { 'action': 'mp_throwcontent_2', 'MedioPay_postid': mp_mypostid, 'MedioPay_outputs': mp_outputs, 'MedioPay_number': mp_numberof_payments, 'MedioPay_userID': mp_userID, 'Mediopay_newCounter': mp_newCounter, 'MedioPay_firstPartner': mp_firstPartner, 'MedioPay_secondPartner': mp_secondPartner, 'MedioPay_thirdPartner': mp_thirdPartner, 'MedioPay_fourthPartner': mp_fourthPartner, 'MedioPay_shareQuote': mp_sharing, 'MedioPay_preview': mp_preview }; console.log("turning data over"); jQuery.post(my_ajax_object.ajax_url, data, function(response) { console.log("unlock 2 " + response); mp_unlockContent2(payment, response); }); }); ``` Then a function is called: ``` add_action ( 'wp_ajax_nopriv_mp_throwcontent_2', 'mp_throwcontent_2' ); function mp_throwcontent_2() { // some ifs and so on // echo "output" } ``` When the plugin starts, Ajax is localized ``` wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); ``` A little quirk: I localized it twice, accidently, here too: ``` wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) ); ``` Can this be a problem? All this works very fine on a few blogs. But in one the operations just stop when the ajax starts. No error, nothing in debug, it just stops. Does anybody have an idea what I can do to make it run? Is there a fallback to call in case it fails? Ah, and to make it even weirder: The plugin worked fine on that blog, but suddenly it stopped working, while the owners tells me he didn't even change anything on his wordpress installation.
I had a similar problem couple years ago. Here's a gist I've published, which shows the basic idea how I solved the problem,<https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d> Applying the gist to your situation I think the solution could be something like this. I didn't test this so it might require some tweaking, but it should at least point you to the right direction. Of course you need to add relevant css for the `ul` elements to position them next to each other. In my example I moved the term and post queries to their own helper functions, but this is just a matter of preference. ``` function archive_categories( string $tax ) { $categories = get_terms($tax); return ( $categories && is_array($categories) ) ? $categories: array(); } function archive_category_posts_query( string $tax, string $term ) { $args = array( 'post_type' => array('custom_post', 'custom_post', 'custom_post'), 'numberposts' => -1, 'orderby' => 'title', 'order' => 'ASC' 'tax_query' => array( array( 'taxonomy' => $tax, 'field' => 'slug', 'terms' => $term, ), ), ); return new WP_Query($args); } $categories = archive_categories('archive_category'); $col_count = 4; foreach ($categories as $category) : $category_posts_query = archive_category_posts_query($category->taxonomy, $category->slug); $post_count = $category_posts_query->found_posts; $posts_per_col = ceil( $post_count / $col_count ); $i = 0; ?> <div> <a data-toggle="collapse" href="#<?php echo $category->slug; ?>"> <h3><?php echo $count; ?><?php echo $category->name; ?></h3> </a> <div class="collapse" id="<?php echo $category->slug; ?>"> <ul> <?php foreach ( $category_posts_query->posts as $category_post ) : if ( $posts_per_col === $i ) { $i = 0; echo '</ul><ul>'; } ?> <li> <a href="<?php esc_url( get_the_permalink( $category_post->ID ) ); ?>"><?php echo esc_html( $category_post->post_title ); ?></a> </li> <?php $i++; endforeach; ?> </ul> </div> <!-- collapse --> </div> <!-- collapse wrapper --> <?php endforeach; ``` **EDIT 5.2.2020** Categories into columns? You mean something like this? ``` $categories = archive_categories('archive_category'); $category_count = count( $categories ); $col_count = 3; $categories_per_col = $category_count > $col_count ? ceil( $category_count / $col_count ) : 1; $column_index = 1; echo '<div class="row">'; foreach ($categories as $category) : $category_posts_query = archive_category_posts_query($category->taxonomy, $category->slug); if ( $column_index > $col_count ) { $column_index = 1; echo '</div><div class="row">'; } $classes = array( 'column_1_of_' . $col_count, 'column-' . $column_index, ); ?> <div class="<?php echo implode( ' ', $classes ); ?>"> <a data-toggle="collapse" href="#<?php echo $category->slug; ?>"> <h3><?php echo $category->count . ' ' . $category->name; ?></h3> </a> <div class="collapse" id="<?php echo $category->slug; ?>"> <ul> <?php foreach ( $category_posts_query->posts as $category_post ) : ?> <li> <a href="<?php esc_url( get_the_permalink( $category_post->ID ) ); ?>"><?php echo esc_html( $category_post->post_title ); ?></a> </li> <?php endforeach; ?> </ul> </div> <!-- collapse --> </div> <!-- collapse wrapper --> <?php $column_index++; endforeach; echo '</div>'; ```
357,765
<p>I want to add a "New" badge to the titles of recent post's widgets. whenever I add any new post from that time to 5 days this "New" badge should show after that it should disappear. this badge is a "new.gif" file. I also added an image for your reference. <a href="https://i.stack.imgur.com/hbmLC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hbmLC.jpg" alt="enter image description here"></a> </p>
[ { "answer_id": 357544, "author": "Waldo Rabie", "author_id": 172667, "author_profile": "https://wordpress.stackexchange.com/users/172667", "pm_score": 0, "selected": false, "text": "<p>The answer is CSS and you've got a couple options! </p>\n\n<pre><code>&lt;?php $categories = get_terms('my_category'); ?&gt;\n\n&lt;ul&gt;\n &lt;?php foreach ( $categories as $index =&gt; $category ): ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php echo get_the_title( $p-&gt;ID ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>You can use Flexbox...</p>\n\n<pre><code>ul {\n display: flex;\n flex-direction: column;\n flex-wrap: wrap;\n height: 306px;\n width: 200px;\n}\nli {\n width: 100px;\n height: 100px;\n}\n</code></pre>\n\n<p>OR, you can use Text Columns</p>\n\n<pre><code>ul {\n column-count: 2;\n column-gap: 0;\n}\nli {\n display: inline-block;\n}\n</code></pre>\n\n<p><a href=\"https://css-tricks.com/arranging-elements-top-bottom-instead-left-right-float/\" rel=\"nofollow noreferrer\">Here's</a> a great resource with further details and codepens.</p>\n" }, { "answer_id": 357591, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": true, "text": "<p>I had a similar problem couple years ago. Here's a gist I've published, which shows the basic idea how I solved the problem,<a href=\"https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d\" rel=\"nofollow noreferrer\">https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d</a></p>\n\n<p>Applying the gist to your situation I think the solution could be something like this. I didn't test this so it might require some tweaking, but it should at least point you to the right direction. Of course you need to add relevant css for the <code>ul</code> elements to position them next to each other.</p>\n\n<p>In my example I moved the term and post queries to their own helper functions, but this is just a matter of preference.</p>\n\n<pre><code>function archive_categories( string $tax ) {\n $categories = get_terms($tax);\n return ( $categories &amp;&amp; is_array($categories) ) ? $categories: array();\n}\n\nfunction archive_category_posts_query( string $tax, string $term ) {\n $args = array(\n 'post_type' =&gt; array('custom_post', 'custom_post', 'custom_post'),\n 'numberposts' =&gt; -1,\n 'orderby' =&gt; 'title',\n 'order' =&gt; 'ASC'\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; $tax,\n 'field' =&gt; 'slug',\n 'terms' =&gt; $term,\n ),\n ),\n );\n return new WP_Query($args);\n}\n\n$categories = archive_categories('archive_category');\n$col_count = 4;\n\nforeach ($categories as $category) :\n $category_posts_query = archive_category_posts_query($category-&gt;taxonomy, $category-&gt;slug);\n $post_count = $category_posts_query-&gt;found_posts;\n $posts_per_col = ceil( $post_count / $col_count );\n $i = 0;\n ?&gt;\n &lt;div&gt;\n &lt;a data-toggle=\"collapse\" href=\"#&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;h3&gt;&lt;?php echo $count; ?&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/h3&gt;\n &lt;/a&gt;\n &lt;div class=\"collapse\" id=\"&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;ul&gt;\n &lt;?php foreach ( $category_posts_query-&gt;posts as $category_post ) : \n if ( $posts_per_col === $i ) {\n $i = 0; \n echo '&lt;/ul&gt;&lt;ul&gt;';\n }\n ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php esc_url( get_the_permalink( $category_post-&gt;ID ) ); ?&gt;\"&gt;&lt;?php echo esc_html( $category_post-&gt;post_title ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php $i++; endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt; &lt;!-- collapse --&gt;\n &lt;/div&gt; &lt;!-- collapse wrapper --&gt;\n&lt;?php endforeach;\n</code></pre>\n\n<p><strong>EDIT 5.2.2020</strong></p>\n\n<p>Categories into columns? You mean something like this?</p>\n\n<pre><code>$categories = archive_categories('archive_category');\n$category_count = count( $categories );\n$col_count = 3;\n$categories_per_col = $category_count &gt; $col_count ? ceil( $category_count / $col_count ) : 1;\n$column_index = 1;\n\necho '&lt;div class=\"row\"&gt;';\nforeach ($categories as $category) :\n $category_posts_query = archive_category_posts_query($category-&gt;taxonomy, $category-&gt;slug);\n if ( $column_index &gt; $col_count ) {\n $column_index = 1;\n echo '&lt;/div&gt;&lt;div class=\"row\"&gt;';\n }\n $classes = array(\n 'column_1_of_' . $col_count,\n 'column-' . $column_index,\n );\n ?&gt;\n &lt;div class=\"&lt;?php echo implode( ' ', $classes ); ?&gt;\"&gt;\n &lt;a data-toggle=\"collapse\" href=\"#&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;h3&gt;&lt;?php echo $category-&gt;count . ' ' . $category-&gt;name; ?&gt;&lt;/h3&gt;\n &lt;/a&gt;\n &lt;div class=\"collapse\" id=\"&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;ul&gt;\n &lt;?php foreach ( $category_posts_query-&gt;posts as $category_post ) : ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php esc_url( get_the_permalink( $category_post-&gt;ID ) ); ?&gt;\"&gt;&lt;?php echo esc_html( $category_post-&gt;post_title ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt; &lt;!-- collapse --&gt;\n &lt;/div&gt; &lt;!-- collapse wrapper --&gt;\n&lt;?php $column_index++; endforeach;\necho '&lt;/div&gt;';\n</code></pre>\n" } ]
2020/02/03
[ "https://wordpress.stackexchange.com/questions/357765", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130910/" ]
I want to add a "New" badge to the titles of recent post's widgets. whenever I add any new post from that time to 5 days this "New" badge should show after that it should disappear. this badge is a "new.gif" file. I also added an image for your reference. [![enter image description here](https://i.stack.imgur.com/hbmLC.jpg)](https://i.stack.imgur.com/hbmLC.jpg)
I had a similar problem couple years ago. Here's a gist I've published, which shows the basic idea how I solved the problem,<https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d> Applying the gist to your situation I think the solution could be something like this. I didn't test this so it might require some tweaking, but it should at least point you to the right direction. Of course you need to add relevant css for the `ul` elements to position them next to each other. In my example I moved the term and post queries to their own helper functions, but this is just a matter of preference. ``` function archive_categories( string $tax ) { $categories = get_terms($tax); return ( $categories && is_array($categories) ) ? $categories: array(); } function archive_category_posts_query( string $tax, string $term ) { $args = array( 'post_type' => array('custom_post', 'custom_post', 'custom_post'), 'numberposts' => -1, 'orderby' => 'title', 'order' => 'ASC' 'tax_query' => array( array( 'taxonomy' => $tax, 'field' => 'slug', 'terms' => $term, ), ), ); return new WP_Query($args); } $categories = archive_categories('archive_category'); $col_count = 4; foreach ($categories as $category) : $category_posts_query = archive_category_posts_query($category->taxonomy, $category->slug); $post_count = $category_posts_query->found_posts; $posts_per_col = ceil( $post_count / $col_count ); $i = 0; ?> <div> <a data-toggle="collapse" href="#<?php echo $category->slug; ?>"> <h3><?php echo $count; ?><?php echo $category->name; ?></h3> </a> <div class="collapse" id="<?php echo $category->slug; ?>"> <ul> <?php foreach ( $category_posts_query->posts as $category_post ) : if ( $posts_per_col === $i ) { $i = 0; echo '</ul><ul>'; } ?> <li> <a href="<?php esc_url( get_the_permalink( $category_post->ID ) ); ?>"><?php echo esc_html( $category_post->post_title ); ?></a> </li> <?php $i++; endforeach; ?> </ul> </div> <!-- collapse --> </div> <!-- collapse wrapper --> <?php endforeach; ``` **EDIT 5.2.2020** Categories into columns? You mean something like this? ``` $categories = archive_categories('archive_category'); $category_count = count( $categories ); $col_count = 3; $categories_per_col = $category_count > $col_count ? ceil( $category_count / $col_count ) : 1; $column_index = 1; echo '<div class="row">'; foreach ($categories as $category) : $category_posts_query = archive_category_posts_query($category->taxonomy, $category->slug); if ( $column_index > $col_count ) { $column_index = 1; echo '</div><div class="row">'; } $classes = array( 'column_1_of_' . $col_count, 'column-' . $column_index, ); ?> <div class="<?php echo implode( ' ', $classes ); ?>"> <a data-toggle="collapse" href="#<?php echo $category->slug; ?>"> <h3><?php echo $category->count . ' ' . $category->name; ?></h3> </a> <div class="collapse" id="<?php echo $category->slug; ?>"> <ul> <?php foreach ( $category_posts_query->posts as $category_post ) : ?> <li> <a href="<?php esc_url( get_the_permalink( $category_post->ID ) ); ?>"><?php echo esc_html( $category_post->post_title ); ?></a> </li> <?php endforeach; ?> </ul> </div> <!-- collapse --> </div> <!-- collapse wrapper --> <?php $column_index++; endforeach; echo '</div>'; ```
357,790
<p>My goal:</p> <p>I want external links to shops I'm affiliated with (for example amazon) to automatically get the affiliate ID attached to it.</p> <p>Example:</p> <p>link I put in my blog post editor <a href="https://rads.stackoverflow.com/amzn/click/com/B07K344J3N" rel="nofollow noreferrer" rel="nofollow noreferrer">https://www.amazon.com/dp/B07K344J3N/</a></p> <p>changes in frontend to <a href="https://rads.stackoverflow.com/amzn/click/com/B07K344J3N" rel="nofollow noreferrer" rel="nofollow noreferrer">https://www.amazon.com/dp/B07K344J3N/?tag=myafftag-02</a></p> <p>What I have found:</p> <p>The creator of the theme I'm using is offering something very close to what I'm looking for:</p> <pre><code>add_action('wpfepp_form_actions', 'link_change_custom'); function link_change_custom($data){ if ( !empty( $_POST['rehub_offer_product_url'] ) ) { $url = $_POST['rehub_offer_product_url']; $checkdomain = 'amazon.com'; if (!empty($url) &amp;&amp; strpos($url, $checkdomain) !== false) : $afftag = 'myafftag-02'; //our affiliate ID $affstring = 'tag='; // url parameter for affiliate ID if (parse_url($url, PHP_URL_QUERY)): //check if link has query string if (strpos($affstring, $url) !== false) : //check if link already has affiliate ID $url = preg_replace("/(".$affstring.").*?(\z|&amp;)/", "$1".$afftag."$2", $url); else: $url = $url.'&amp;'.$affstring.$afftag; endif; else: $url = $url.'?'.$affstring.$afftag; endif; endif; update_post_meta( $data['post_id'], 'rehub_offer_product_url', esc_url($url) ); } } </code></pre> <p>The problem:</p> <p>It only works on links that are stored in the field "rehub_offer_product_url", but I want it to work on any links to amazon I put in the content of my blog posts.</p> <p>I appreciate any help.</p>
[ { "answer_id": 357544, "author": "Waldo Rabie", "author_id": 172667, "author_profile": "https://wordpress.stackexchange.com/users/172667", "pm_score": 0, "selected": false, "text": "<p>The answer is CSS and you've got a couple options! </p>\n\n<pre><code>&lt;?php $categories = get_terms('my_category'); ?&gt;\n\n&lt;ul&gt;\n &lt;?php foreach ( $categories as $index =&gt; $category ): ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php echo get_the_title( $p-&gt;ID ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>You can use Flexbox...</p>\n\n<pre><code>ul {\n display: flex;\n flex-direction: column;\n flex-wrap: wrap;\n height: 306px;\n width: 200px;\n}\nli {\n width: 100px;\n height: 100px;\n}\n</code></pre>\n\n<p>OR, you can use Text Columns</p>\n\n<pre><code>ul {\n column-count: 2;\n column-gap: 0;\n}\nli {\n display: inline-block;\n}\n</code></pre>\n\n<p><a href=\"https://css-tricks.com/arranging-elements-top-bottom-instead-left-right-float/\" rel=\"nofollow noreferrer\">Here's</a> a great resource with further details and codepens.</p>\n" }, { "answer_id": 357591, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": true, "text": "<p>I had a similar problem couple years ago. Here's a gist I've published, which shows the basic idea how I solved the problem,<a href=\"https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d\" rel=\"nofollow noreferrer\">https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d</a></p>\n\n<p>Applying the gist to your situation I think the solution could be something like this. I didn't test this so it might require some tweaking, but it should at least point you to the right direction. Of course you need to add relevant css for the <code>ul</code> elements to position them next to each other.</p>\n\n<p>In my example I moved the term and post queries to their own helper functions, but this is just a matter of preference.</p>\n\n<pre><code>function archive_categories( string $tax ) {\n $categories = get_terms($tax);\n return ( $categories &amp;&amp; is_array($categories) ) ? $categories: array();\n}\n\nfunction archive_category_posts_query( string $tax, string $term ) {\n $args = array(\n 'post_type' =&gt; array('custom_post', 'custom_post', 'custom_post'),\n 'numberposts' =&gt; -1,\n 'orderby' =&gt; 'title',\n 'order' =&gt; 'ASC'\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; $tax,\n 'field' =&gt; 'slug',\n 'terms' =&gt; $term,\n ),\n ),\n );\n return new WP_Query($args);\n}\n\n$categories = archive_categories('archive_category');\n$col_count = 4;\n\nforeach ($categories as $category) :\n $category_posts_query = archive_category_posts_query($category-&gt;taxonomy, $category-&gt;slug);\n $post_count = $category_posts_query-&gt;found_posts;\n $posts_per_col = ceil( $post_count / $col_count );\n $i = 0;\n ?&gt;\n &lt;div&gt;\n &lt;a data-toggle=\"collapse\" href=\"#&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;h3&gt;&lt;?php echo $count; ?&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/h3&gt;\n &lt;/a&gt;\n &lt;div class=\"collapse\" id=\"&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;ul&gt;\n &lt;?php foreach ( $category_posts_query-&gt;posts as $category_post ) : \n if ( $posts_per_col === $i ) {\n $i = 0; \n echo '&lt;/ul&gt;&lt;ul&gt;';\n }\n ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php esc_url( get_the_permalink( $category_post-&gt;ID ) ); ?&gt;\"&gt;&lt;?php echo esc_html( $category_post-&gt;post_title ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php $i++; endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt; &lt;!-- collapse --&gt;\n &lt;/div&gt; &lt;!-- collapse wrapper --&gt;\n&lt;?php endforeach;\n</code></pre>\n\n<p><strong>EDIT 5.2.2020</strong></p>\n\n<p>Categories into columns? You mean something like this?</p>\n\n<pre><code>$categories = archive_categories('archive_category');\n$category_count = count( $categories );\n$col_count = 3;\n$categories_per_col = $category_count &gt; $col_count ? ceil( $category_count / $col_count ) : 1;\n$column_index = 1;\n\necho '&lt;div class=\"row\"&gt;';\nforeach ($categories as $category) :\n $category_posts_query = archive_category_posts_query($category-&gt;taxonomy, $category-&gt;slug);\n if ( $column_index &gt; $col_count ) {\n $column_index = 1;\n echo '&lt;/div&gt;&lt;div class=\"row\"&gt;';\n }\n $classes = array(\n 'column_1_of_' . $col_count,\n 'column-' . $column_index,\n );\n ?&gt;\n &lt;div class=\"&lt;?php echo implode( ' ', $classes ); ?&gt;\"&gt;\n &lt;a data-toggle=\"collapse\" href=\"#&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;h3&gt;&lt;?php echo $category-&gt;count . ' ' . $category-&gt;name; ?&gt;&lt;/h3&gt;\n &lt;/a&gt;\n &lt;div class=\"collapse\" id=\"&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;ul&gt;\n &lt;?php foreach ( $category_posts_query-&gt;posts as $category_post ) : ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php esc_url( get_the_permalink( $category_post-&gt;ID ) ); ?&gt;\"&gt;&lt;?php echo esc_html( $category_post-&gt;post_title ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt; &lt;!-- collapse --&gt;\n &lt;/div&gt; &lt;!-- collapse wrapper --&gt;\n&lt;?php $column_index++; endforeach;\necho '&lt;/div&gt;';\n</code></pre>\n" } ]
2020/02/03
[ "https://wordpress.stackexchange.com/questions/357790", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/182082/" ]
My goal: I want external links to shops I'm affiliated with (for example amazon) to automatically get the affiliate ID attached to it. Example: link I put in my blog post editor [https://www.amazon.com/dp/B07K344J3N/](https://rads.stackoverflow.com/amzn/click/com/B07K344J3N) changes in frontend to [https://www.amazon.com/dp/B07K344J3N/?tag=myafftag-02](https://rads.stackoverflow.com/amzn/click/com/B07K344J3N) What I have found: The creator of the theme I'm using is offering something very close to what I'm looking for: ``` add_action('wpfepp_form_actions', 'link_change_custom'); function link_change_custom($data){ if ( !empty( $_POST['rehub_offer_product_url'] ) ) { $url = $_POST['rehub_offer_product_url']; $checkdomain = 'amazon.com'; if (!empty($url) && strpos($url, $checkdomain) !== false) : $afftag = 'myafftag-02'; //our affiliate ID $affstring = 'tag='; // url parameter for affiliate ID if (parse_url($url, PHP_URL_QUERY)): //check if link has query string if (strpos($affstring, $url) !== false) : //check if link already has affiliate ID $url = preg_replace("/(".$affstring.").*?(\z|&)/", "$1".$afftag."$2", $url); else: $url = $url.'&'.$affstring.$afftag; endif; else: $url = $url.'?'.$affstring.$afftag; endif; endif; update_post_meta( $data['post_id'], 'rehub_offer_product_url', esc_url($url) ); } } ``` The problem: It only works on links that are stored in the field "rehub\_offer\_product\_url", but I want it to work on any links to amazon I put in the content of my blog posts. I appreciate any help.
I had a similar problem couple years ago. Here's a gist I've published, which shows the basic idea how I solved the problem,<https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d> Applying the gist to your situation I think the solution could be something like this. I didn't test this so it might require some tweaking, but it should at least point you to the right direction. Of course you need to add relevant css for the `ul` elements to position them next to each other. In my example I moved the term and post queries to their own helper functions, but this is just a matter of preference. ``` function archive_categories( string $tax ) { $categories = get_terms($tax); return ( $categories && is_array($categories) ) ? $categories: array(); } function archive_category_posts_query( string $tax, string $term ) { $args = array( 'post_type' => array('custom_post', 'custom_post', 'custom_post'), 'numberposts' => -1, 'orderby' => 'title', 'order' => 'ASC' 'tax_query' => array( array( 'taxonomy' => $tax, 'field' => 'slug', 'terms' => $term, ), ), ); return new WP_Query($args); } $categories = archive_categories('archive_category'); $col_count = 4; foreach ($categories as $category) : $category_posts_query = archive_category_posts_query($category->taxonomy, $category->slug); $post_count = $category_posts_query->found_posts; $posts_per_col = ceil( $post_count / $col_count ); $i = 0; ?> <div> <a data-toggle="collapse" href="#<?php echo $category->slug; ?>"> <h3><?php echo $count; ?><?php echo $category->name; ?></h3> </a> <div class="collapse" id="<?php echo $category->slug; ?>"> <ul> <?php foreach ( $category_posts_query->posts as $category_post ) : if ( $posts_per_col === $i ) { $i = 0; echo '</ul><ul>'; } ?> <li> <a href="<?php esc_url( get_the_permalink( $category_post->ID ) ); ?>"><?php echo esc_html( $category_post->post_title ); ?></a> </li> <?php $i++; endforeach; ?> </ul> </div> <!-- collapse --> </div> <!-- collapse wrapper --> <?php endforeach; ``` **EDIT 5.2.2020** Categories into columns? You mean something like this? ``` $categories = archive_categories('archive_category'); $category_count = count( $categories ); $col_count = 3; $categories_per_col = $category_count > $col_count ? ceil( $category_count / $col_count ) : 1; $column_index = 1; echo '<div class="row">'; foreach ($categories as $category) : $category_posts_query = archive_category_posts_query($category->taxonomy, $category->slug); if ( $column_index > $col_count ) { $column_index = 1; echo '</div><div class="row">'; } $classes = array( 'column_1_of_' . $col_count, 'column-' . $column_index, ); ?> <div class="<?php echo implode( ' ', $classes ); ?>"> <a data-toggle="collapse" href="#<?php echo $category->slug; ?>"> <h3><?php echo $category->count . ' ' . $category->name; ?></h3> </a> <div class="collapse" id="<?php echo $category->slug; ?>"> <ul> <?php foreach ( $category_posts_query->posts as $category_post ) : ?> <li> <a href="<?php esc_url( get_the_permalink( $category_post->ID ) ); ?>"><?php echo esc_html( $category_post->post_title ); ?></a> </li> <?php endforeach; ?> </ul> </div> <!-- collapse --> </div> <!-- collapse wrapper --> <?php $column_index++; endforeach; echo '</div>'; ```
357,827
<p>I had started my wordpress site with the host SiteGround. Later I moved to another host.</p> <p>I now see that in my wp-config.php file the following settings are present near the end of the file:</p> <pre><code>/* That's all, stop editing! Happy blogging. */ /** Absolute path to the WordPress directory. */ if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); /** Sets up WordPress vars and included files. */ require_once(ABSPATH . 'wp-settings.php'); # Disables all core updates. Added by SiteGround Autoupdate: define( 'WP_AUTO_UPDATE_CORE', false ); @include_once('/var/lib/sec/wp-settings.php'); // Added by SiteGround WordPress management system </code></pre> <p>Does anyone know whether or not I should let these settings remain as they are? I'm particularly suspicious about the third one - disabling auto-core updates.</p> <p>Is it better to keep core updates disabled or enabled?</p>
[ { "answer_id": 357544, "author": "Waldo Rabie", "author_id": 172667, "author_profile": "https://wordpress.stackexchange.com/users/172667", "pm_score": 0, "selected": false, "text": "<p>The answer is CSS and you've got a couple options! </p>\n\n<pre><code>&lt;?php $categories = get_terms('my_category'); ?&gt;\n\n&lt;ul&gt;\n &lt;?php foreach ( $categories as $index =&gt; $category ): ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php echo get_the_title( $p-&gt;ID ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>You can use Flexbox...</p>\n\n<pre><code>ul {\n display: flex;\n flex-direction: column;\n flex-wrap: wrap;\n height: 306px;\n width: 200px;\n}\nli {\n width: 100px;\n height: 100px;\n}\n</code></pre>\n\n<p>OR, you can use Text Columns</p>\n\n<pre><code>ul {\n column-count: 2;\n column-gap: 0;\n}\nli {\n display: inline-block;\n}\n</code></pre>\n\n<p><a href=\"https://css-tricks.com/arranging-elements-top-bottom-instead-left-right-float/\" rel=\"nofollow noreferrer\">Here's</a> a great resource with further details and codepens.</p>\n" }, { "answer_id": 357591, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": true, "text": "<p>I had a similar problem couple years ago. Here's a gist I've published, which shows the basic idea how I solved the problem,<a href=\"https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d\" rel=\"nofollow noreferrer\">https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d</a></p>\n\n<p>Applying the gist to your situation I think the solution could be something like this. I didn't test this so it might require some tweaking, but it should at least point you to the right direction. Of course you need to add relevant css for the <code>ul</code> elements to position them next to each other.</p>\n\n<p>In my example I moved the term and post queries to their own helper functions, but this is just a matter of preference.</p>\n\n<pre><code>function archive_categories( string $tax ) {\n $categories = get_terms($tax);\n return ( $categories &amp;&amp; is_array($categories) ) ? $categories: array();\n}\n\nfunction archive_category_posts_query( string $tax, string $term ) {\n $args = array(\n 'post_type' =&gt; array('custom_post', 'custom_post', 'custom_post'),\n 'numberposts' =&gt; -1,\n 'orderby' =&gt; 'title',\n 'order' =&gt; 'ASC'\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; $tax,\n 'field' =&gt; 'slug',\n 'terms' =&gt; $term,\n ),\n ),\n );\n return new WP_Query($args);\n}\n\n$categories = archive_categories('archive_category');\n$col_count = 4;\n\nforeach ($categories as $category) :\n $category_posts_query = archive_category_posts_query($category-&gt;taxonomy, $category-&gt;slug);\n $post_count = $category_posts_query-&gt;found_posts;\n $posts_per_col = ceil( $post_count / $col_count );\n $i = 0;\n ?&gt;\n &lt;div&gt;\n &lt;a data-toggle=\"collapse\" href=\"#&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;h3&gt;&lt;?php echo $count; ?&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/h3&gt;\n &lt;/a&gt;\n &lt;div class=\"collapse\" id=\"&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;ul&gt;\n &lt;?php foreach ( $category_posts_query-&gt;posts as $category_post ) : \n if ( $posts_per_col === $i ) {\n $i = 0; \n echo '&lt;/ul&gt;&lt;ul&gt;';\n }\n ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php esc_url( get_the_permalink( $category_post-&gt;ID ) ); ?&gt;\"&gt;&lt;?php echo esc_html( $category_post-&gt;post_title ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php $i++; endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt; &lt;!-- collapse --&gt;\n &lt;/div&gt; &lt;!-- collapse wrapper --&gt;\n&lt;?php endforeach;\n</code></pre>\n\n<p><strong>EDIT 5.2.2020</strong></p>\n\n<p>Categories into columns? You mean something like this?</p>\n\n<pre><code>$categories = archive_categories('archive_category');\n$category_count = count( $categories );\n$col_count = 3;\n$categories_per_col = $category_count &gt; $col_count ? ceil( $category_count / $col_count ) : 1;\n$column_index = 1;\n\necho '&lt;div class=\"row\"&gt;';\nforeach ($categories as $category) :\n $category_posts_query = archive_category_posts_query($category-&gt;taxonomy, $category-&gt;slug);\n if ( $column_index &gt; $col_count ) {\n $column_index = 1;\n echo '&lt;/div&gt;&lt;div class=\"row\"&gt;';\n }\n $classes = array(\n 'column_1_of_' . $col_count,\n 'column-' . $column_index,\n );\n ?&gt;\n &lt;div class=\"&lt;?php echo implode( ' ', $classes ); ?&gt;\"&gt;\n &lt;a data-toggle=\"collapse\" href=\"#&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;h3&gt;&lt;?php echo $category-&gt;count . ' ' . $category-&gt;name; ?&gt;&lt;/h3&gt;\n &lt;/a&gt;\n &lt;div class=\"collapse\" id=\"&lt;?php echo $category-&gt;slug; ?&gt;\"&gt;\n &lt;ul&gt;\n &lt;?php foreach ( $category_posts_query-&gt;posts as $category_post ) : ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php esc_url( get_the_permalink( $category_post-&gt;ID ) ); ?&gt;\"&gt;&lt;?php echo esc_html( $category_post-&gt;post_title ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt; &lt;!-- collapse --&gt;\n &lt;/div&gt; &lt;!-- collapse wrapper --&gt;\n&lt;?php $column_index++; endforeach;\necho '&lt;/div&gt;';\n</code></pre>\n" } ]
2020/02/04
[ "https://wordpress.stackexchange.com/questions/357827", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167402/" ]
I had started my wordpress site with the host SiteGround. Later I moved to another host. I now see that in my wp-config.php file the following settings are present near the end of the file: ``` /* That's all, stop editing! Happy blogging. */ /** Absolute path to the WordPress directory. */ if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); /** Sets up WordPress vars and included files. */ require_once(ABSPATH . 'wp-settings.php'); # Disables all core updates. Added by SiteGround Autoupdate: define( 'WP_AUTO_UPDATE_CORE', false ); @include_once('/var/lib/sec/wp-settings.php'); // Added by SiteGround WordPress management system ``` Does anyone know whether or not I should let these settings remain as they are? I'm particularly suspicious about the third one - disabling auto-core updates. Is it better to keep core updates disabled or enabled?
I had a similar problem couple years ago. Here's a gist I've published, which shows the basic idea how I solved the problem,<https://gist.github.com/koskinenaa/4d8461116885c0e64d5ca167ae53434d> Applying the gist to your situation I think the solution could be something like this. I didn't test this so it might require some tweaking, but it should at least point you to the right direction. Of course you need to add relevant css for the `ul` elements to position them next to each other. In my example I moved the term and post queries to their own helper functions, but this is just a matter of preference. ``` function archive_categories( string $tax ) { $categories = get_terms($tax); return ( $categories && is_array($categories) ) ? $categories: array(); } function archive_category_posts_query( string $tax, string $term ) { $args = array( 'post_type' => array('custom_post', 'custom_post', 'custom_post'), 'numberposts' => -1, 'orderby' => 'title', 'order' => 'ASC' 'tax_query' => array( array( 'taxonomy' => $tax, 'field' => 'slug', 'terms' => $term, ), ), ); return new WP_Query($args); } $categories = archive_categories('archive_category'); $col_count = 4; foreach ($categories as $category) : $category_posts_query = archive_category_posts_query($category->taxonomy, $category->slug); $post_count = $category_posts_query->found_posts; $posts_per_col = ceil( $post_count / $col_count ); $i = 0; ?> <div> <a data-toggle="collapse" href="#<?php echo $category->slug; ?>"> <h3><?php echo $count; ?><?php echo $category->name; ?></h3> </a> <div class="collapse" id="<?php echo $category->slug; ?>"> <ul> <?php foreach ( $category_posts_query->posts as $category_post ) : if ( $posts_per_col === $i ) { $i = 0; echo '</ul><ul>'; } ?> <li> <a href="<?php esc_url( get_the_permalink( $category_post->ID ) ); ?>"><?php echo esc_html( $category_post->post_title ); ?></a> </li> <?php $i++; endforeach; ?> </ul> </div> <!-- collapse --> </div> <!-- collapse wrapper --> <?php endforeach; ``` **EDIT 5.2.2020** Categories into columns? You mean something like this? ``` $categories = archive_categories('archive_category'); $category_count = count( $categories ); $col_count = 3; $categories_per_col = $category_count > $col_count ? ceil( $category_count / $col_count ) : 1; $column_index = 1; echo '<div class="row">'; foreach ($categories as $category) : $category_posts_query = archive_category_posts_query($category->taxonomy, $category->slug); if ( $column_index > $col_count ) { $column_index = 1; echo '</div><div class="row">'; } $classes = array( 'column_1_of_' . $col_count, 'column-' . $column_index, ); ?> <div class="<?php echo implode( ' ', $classes ); ?>"> <a data-toggle="collapse" href="#<?php echo $category->slug; ?>"> <h3><?php echo $category->count . ' ' . $category->name; ?></h3> </a> <div class="collapse" id="<?php echo $category->slug; ?>"> <ul> <?php foreach ( $category_posts_query->posts as $category_post ) : ?> <li> <a href="<?php esc_url( get_the_permalink( $category_post->ID ) ); ?>"><?php echo esc_html( $category_post->post_title ); ?></a> </li> <?php endforeach; ?> </ul> </div> <!-- collapse --> </div> <!-- collapse wrapper --> <?php $column_index++; endforeach; echo '</div>'; ```
357,831
<p>I am developing a Form in Admin Panel. My Form code is like below</p> <pre><code>&lt;form method="post" action="&lt;?php echo home_url(add_query_arg(array(), $wp-&gt;request));?&gt;" name="newAddress" id="createuser" class="validate" novalidate="novalidate"&gt; </code></pre> <p>My Current URL is like below</p> <pre><code>http://localhost/wordpress123/wp-admin/admin.php?page=newAddress </code></pre> <p>I need below code in Form</p> <pre><code>&lt;form method="post" action="/wordpress123/wp-admin/admin.php?page=newAddress" name="newAddress" id="createuser" class="validate" novalidate="novalidate"&gt; </code></pre>
[ { "answer_id": 357834, "author": "Patryk Parcheta", "author_id": 181863, "author_profile": "https://wordpress.stackexchange.com/users/181863", "pm_score": 2, "selected": true, "text": "<p>Just use <code>$_SERVER['REQUEST_URI'];</code> instead of <code>home_url(add_query_arg(array(), $wp-&gt;request));</code></p>\n" }, { "answer_id": 357895, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": -1, "selected": false, "text": "<p>Forms submit to the current URL by default. Just leave the action parameter out if you want it to be the current URL.</p>\n\n<pre><code>&lt;form method=\"post\" name=\"newAddress\" id=\"createuser\" class=\"validate\" novalidate=\"novalidate\"&gt;\n</code></pre>\n" } ]
2020/02/04
[ "https://wordpress.stackexchange.com/questions/357831", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65189/" ]
I am developing a Form in Admin Panel. My Form code is like below ``` <form method="post" action="<?php echo home_url(add_query_arg(array(), $wp->request));?>" name="newAddress" id="createuser" class="validate" novalidate="novalidate"> ``` My Current URL is like below ``` http://localhost/wordpress123/wp-admin/admin.php?page=newAddress ``` I need below code in Form ``` <form method="post" action="/wordpress123/wp-admin/admin.php?page=newAddress" name="newAddress" id="createuser" class="validate" novalidate="novalidate"> ```
Just use `$_SERVER['REQUEST_URI'];` instead of `home_url(add_query_arg(array(), $wp->request));`
357,851
<p>Using <code>add_theme_support( 'editor-color-palette' )</code> one can replace the color palette in the Gutenberg editor by a custom one:</p> <pre><code>add_theme_support( 'editor-color-palette', array( array( 'name' =&gt; __( 'Strong magenta', 'themeLangDomain' ), 'slug' =&gt; 'strong-magenta', 'color' =&gt; '#a156b4', ), array( 'name' =&gt; __( 'Light grayish magenta', 'themeLangDomain' ), 'slug' =&gt; 'light-grayish-magenta', 'color' =&gt; '#d0a5db', ), ) ); </code></pre> <p>My question is, is there a way to ADD colors to an existing palette (via a child theme, for example) without completely replacing it?</p> <p>Thanks in advance</p>
[ { "answer_id": 357855, "author": "Vitauts Stočka", "author_id": 181289, "author_profile": "https://wordpress.stackexchange.com/users/181289", "pm_score": 3, "selected": false, "text": "<p>You can merge palettes</p>\n\n<pre><code>$existing = get_theme_support( 'editor-color-palette' );\n\n$new = array_merge( $existing[0], array(\n array(\n 'name' =&gt; __( 'Strong magenta', 'themeLangDomain' ),\n 'slug' =&gt; 'strong-magenta',\n 'color' =&gt; '#a156b4',\n ),\n array(\n 'name' =&gt; __( 'Light grayish magenta', 'themeLangDomain' ),\n 'slug' =&gt; 'light-grayish-magenta',\n 'color' =&gt; '#d0a5db',\n ),\n));\n\nadd_theme_support( 'editor-color-palette', $new);\n</code></pre>\n" }, { "answer_id": 357856, "author": "Tim Elsass", "author_id": 80375, "author_profile": "https://wordpress.stackexchange.com/users/80375", "pm_score": 2, "selected": false, "text": "<p>The best way would be to expose the data, so it can be modified. You can do this by adding a filter:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_theme_support( 'editor-color-palette', apply_filters( 'themeLangDomain_editor_color_palette_args', array(\n array(\n 'name' =&gt; __( 'Strong magenta', 'themeLangDomain' ),\n 'slug' =&gt; 'strong-magenta',\n 'color' =&gt; '#a156b4',\n ),\n array(\n 'name' =&gt; __( 'Light grayish magenta', 'themeLangDomain' ),\n 'slug' =&gt; 'light-grayish-magenta',\n 'color' =&gt; '#d0a5db',\n ),\n) ) );\n</code></pre>\n\n<p>Then child themes or plugins can modify the array using <code>add_filter</code> to modify the data in <code>themeLangDomain_editor_color_palette_arg</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'themeLangDomain_editor_color_palette_args', function( $palette ) {\n $palette[] = array(\n 'name' =&gt; __( 'Black', 'themeLangDomain' ),\n 'slug' =&gt; 'black',\n 'color' =&gt; '#000000',\n );\n return $palette;\n} );\n</code></pre>\n" }, { "answer_id": 397613, "author": "Rhys Wynne", "author_id": 9918, "author_profile": "https://wordpress.stackexchange.com/users/9918", "pm_score": 2, "selected": false, "text": "<p>To expand on Vitatus' answer, it works best if you're using a child theme, or a plugin, that edits the above.</p>\n<p>Assuming that the <code>editor-colour-palette</code> is called within a action with a default priority, you can call it after (usually calling <code>after_setup_theme</code> with a priority greater than 10)</p>\n<p>e.g.</p>\n<pre><code>/**\n * Add the pink colour to the site\n *\n * @return void\n */\nfunction wpquestion357851_add_colours()\n{\n\n $existing = get_theme_support('editor-color-palette');\n\n $new = array_merge($existing[0], array(\n array(\n 'name' =&gt; __('Pink', 'twentytwenty'),\n 'slug' =&gt; 'pink',\n 'color' =&gt; '#ff14a7',\n ),\n ));\n\n add_theme_support('editor-color-palette', $new);\n}\nadd_action('after_setup_theme', 'wpquestion357851_add_colours', 20);\n</code></pre>\n<p>You may need to see where the <code>add_theme_support('editor-color-palette'</code> is called within your theme, and make sure it is called after.</p>\n" } ]
2020/02/04
[ "https://wordpress.stackexchange.com/questions/357851", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33049/" ]
Using `add_theme_support( 'editor-color-palette' )` one can replace the color palette in the Gutenberg editor by a custom one: ``` add_theme_support( 'editor-color-palette', array( array( 'name' => __( 'Strong magenta', 'themeLangDomain' ), 'slug' => 'strong-magenta', 'color' => '#a156b4', ), array( 'name' => __( 'Light grayish magenta', 'themeLangDomain' ), 'slug' => 'light-grayish-magenta', 'color' => '#d0a5db', ), ) ); ``` My question is, is there a way to ADD colors to an existing palette (via a child theme, for example) without completely replacing it? Thanks in advance
You can merge palettes ``` $existing = get_theme_support( 'editor-color-palette' ); $new = array_merge( $existing[0], array( array( 'name' => __( 'Strong magenta', 'themeLangDomain' ), 'slug' => 'strong-magenta', 'color' => '#a156b4', ), array( 'name' => __( 'Light grayish magenta', 'themeLangDomain' ), 'slug' => 'light-grayish-magenta', 'color' => '#d0a5db', ), )); add_theme_support( 'editor-color-palette', $new); ```
357,852
<p>I am learning WordPress plugin development. Now I need to place jQuery code in one file. Where can I place jQuery code ?</p>
[ { "answer_id": 357863, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>You should place your javascript inside a <code>.js</code> file in your plugin, then enqueue it using the <code>wp_enqueue_script</code> function on the appropriate hook. Be sure to declare <code>jquery</code> as a dependency when you call <code>wp_enqueue_script</code>, and be sure to call it on the correct hook or WordPress will complain</p>\n" }, { "answer_id": 357866, "author": "Cadu De Castro Alves", "author_id": 122204, "author_profile": "https://wordpress.stackexchange.com/users/122204", "pm_score": 3, "selected": true, "text": "<p>You should place the <code>.js</code> file into your plugin directory (it can be root or any other folder like <code>assets</code> or <code>js</code>).</p>\n\n<h3>To enqueue JS and CSS files in the front-end:</h3>\n\n<pre><code>function wp_357866_enqueue_frontend()\n{\n wp_enqueue_script('your-script', get_template_directory_uri() . '/path/to/js/your-script.js', array(), null, true); // You should set the last parameter to 'true' to load JS in the footer\n wp_enqueue_style('your-style', get_stylesheet_directory_uri() . '/path/to/css/your-style.css', array(), null);\n}\nadd_action( 'wp_enqueue_scripts', 'wp_357866_enqueue_frontend' );\n</code></pre>\n\n<p>Reference: <a href=\"https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/\" rel=\"nofollow noreferrer\">wp_enqueue_scripts</a></p>\n\n<h3>To enqueue JS and CSS in the administration:</h3>\n\n<pre><code>function wp_357866_enqueue_admin()\n{\n wp_enqueue_script('your-script', get_template_directory_uri() . '/path/to/js/your-script.js', array(), null, true); // You should set the last parameter to 'true' to load JS in the footer\n wp_enqueue_style('your-style', get_stylesheet_directory_uri() . '/path/to/css/your-style.css', array(), null);\n}\nadd_action( 'admin_enqueue_scripts', 'wp_357866_enqueue_admin' );\n</code></pre>\n\n<p>Reference: <a href=\"https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/\" rel=\"nofollow noreferrer\">admin_enqueue_scripts</a></p>\n" } ]
2020/02/04
[ "https://wordpress.stackexchange.com/questions/357852", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65189/" ]
I am learning WordPress plugin development. Now I need to place jQuery code in one file. Where can I place jQuery code ?
You should place the `.js` file into your plugin directory (it can be root or any other folder like `assets` or `js`). ### To enqueue JS and CSS files in the front-end: ``` function wp_357866_enqueue_frontend() { wp_enqueue_script('your-script', get_template_directory_uri() . '/path/to/js/your-script.js', array(), null, true); // You should set the last parameter to 'true' to load JS in the footer wp_enqueue_style('your-style', get_stylesheet_directory_uri() . '/path/to/css/your-style.css', array(), null); } add_action( 'wp_enqueue_scripts', 'wp_357866_enqueue_frontend' ); ``` Reference: [wp\_enqueue\_scripts](https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/) ### To enqueue JS and CSS in the administration: ``` function wp_357866_enqueue_admin() { wp_enqueue_script('your-script', get_template_directory_uri() . '/path/to/js/your-script.js', array(), null, true); // You should set the last parameter to 'true' to load JS in the footer wp_enqueue_style('your-style', get_stylesheet_directory_uri() . '/path/to/css/your-style.css', array(), null); } add_action( 'admin_enqueue_scripts', 'wp_357866_enqueue_admin' ); ``` Reference: [admin\_enqueue\_scripts](https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/)
357,864
<p>I'm trying to get a link from a custom post with a custom taxonomy but I'm running into issues trying to get it. I'm wanting to send the user straight to the post if the taxonomy count is 1. If it's greater than one post, it goes to a page showing all the posts of the taxonomy. I have this second part working, but I can't get the first bit to work, I can't get the taxonomy to return the post. </p> <pre><code> &lt;?php $taxonomy = 'treatment_type'; $terms = get_terms($taxonomy); // Get all terms of a taxonomy //print_r($terms ); if ( $terms &amp;&amp; !is_wp_error( $terms ) ) :?&gt; &lt;?php foreach ( $terms as $term ) { if('trending-treatment' !== $term-&gt;slug &amp;&amp; 'skin-care' !== $term-&gt;slug){ ?&gt; &lt;?php if($term-&gt;count == 1){?&gt; &lt;?php $posts_array = get_posts( array( 'showposts' =&gt; -1, 'post_type' =&gt; 'treatment', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'treatment_type', 'field' =&gt; 'term_id', 'terms' =&gt; $term-&gt;slug, ) ) ) ); print_r( $posts_array ); ?&gt; &lt;h1&gt;only 1&lt;/h1&gt; &lt;?php print_r($term); ?&gt; &lt;article class="portfolio-item pf-rejuv"&gt; &lt;div class="portfolio-image"&gt; &lt;a href="POST LINK TO GO HERE"&gt; &lt;img src="&lt;?php the_field('image', $term); ?&gt;" alt="&lt;?php echo $term-&gt;name; ?&gt;"&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="portfolio-desc"&gt; &lt;div class="team-title"&gt;&lt;h4&gt;&lt;?php echo $term-&gt;name; ?&gt;&lt;/h4&gt;&lt;span&gt; &lt;?php the_field('types_of_treatments', $term); ?&gt;&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; &lt;/article&gt; &lt;?php }else{ ?&gt; &lt;article class="portfolio-item pf-rejuv"&gt; &lt;div class="portfolio-image"&gt; &lt;a href="&lt;?php echo get_term_link($term-&gt;slug, $taxonomy); ?&gt;"&gt; &lt;img src="&lt;?php the_field('image', $term); ?&gt;" alt="&lt;?php echo $term-&gt;name; ?&gt;"&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="portfolio-desc"&gt; &lt;div class="team-title"&gt;&lt;h4&gt;&lt;?php echo $term-&gt;name; ?&gt;&lt;/h4&gt;&lt;span&gt; &lt;?php the_field('types_of_treatments', $term); ?&gt;&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; &lt;/article&gt; &lt;?php } ?&gt; &lt;?php } } ?&gt; &lt;?php endif;?&gt; </code></pre>
[ { "answer_id": 357919, "author": "rajat.gite", "author_id": 180636, "author_profile": "https://wordpress.stackexchange.com/users/180636", "pm_score": 0, "selected": false, "text": "<p>Here is my working code brother you can try this.</p>\n\n<pre><code>$terms = get_terms( array(\n 'taxonomy' =&gt; 'market-place',\n 'hide_empty' =&gt; false,\n 'orderby' =&gt; 'term_id',\n 'order' =&gt; 'asc',\n) );\nforeach ($terms as $terms_row) {\n $terms_row-&gt;slug;\n ?&gt;\n &lt;label class=\"cont\"&gt;&lt;?php echo $terms_row-&gt;name;?&gt;\n &lt;input type=\"checkbox\" &lt;?php if(in_array($terms_row-&gt;slug, $market_place_array)){ echo \"checked\"; } ?&gt; class=\"filter\" value = \"&lt;?php echo $terms_row-&gt;slug;?&gt;\" id=\"&lt;?php\n echo $terms_row-&gt;slug;?&gt;\" name=\"products_market\"&gt;\n &lt;span class=\"checkmark\"&gt;&lt;/span&gt;\n &lt;/label&gt;\n &lt;?php\n}\n</code></pre>\n\n<p>Thanks</p>\n" }, { "answer_id": 357924, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>I can't get the first bit to work, I can't get the taxonomy to return\n the post.</p>\n</blockquote>\n\n<p>So the following is the first bit which queries posts in a single taxonomy term:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$posts_array = get_posts(\n array( 'showposts' =&gt; -1,\n 'post_type' =&gt; 'treatment',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'treatment_type',\n 'field' =&gt; 'term_id',\n 'terms' =&gt; $term-&gt;slug,\n )\n )\n )\n);\n</code></pre>\n\n<p>And the problem there is that the <code>tax_query</code>'s <code>field</code> and <code>terms</code> values don't match — you set the <code>field</code> to <code>term_id</code> (term ID), but then the <code>terms</code> is a term slug and not ID.</p>\n\n<p>So make sure they match:</p>\n\n<ul>\n<li><p>Change the <code>'field' =&gt; 'term_id'</code> to <code>'field' =&gt; 'slug'</code>.</p></li>\n<li><p>Or change the <code>'terms' =&gt; $term-&gt;slug</code> to <code>'terms' =&gt; $term-&gt;term_id</code>.</p></li>\n</ul>\n\n<p>And actually, you should use the parameter <code>numberposts</code> or better <code>posts_per_page</code> and not <code>showposts</code> (which is <em>not</em> a standard parameter for <code>get_posts()</code> or <code>WP_Query</code>).</p>\n" }, { "answer_id": 357945, "author": "richerimage", "author_id": 57057, "author_profile": "https://wordpress.stackexchange.com/users/57057", "pm_score": 0, "selected": false, "text": "<p>This should work...</p>\n\n<pre><code>$query = new WP_Query( $args );\n$count = $query-&gt;found_posts; // will return number of posts i your query\n\nif ( $query-&gt;have_posts() ) {\n\n while ( $query-&gt;have_posts() ) {\n\n $query-&gt;the_post();\n\n if($count == 1) { // if there's just one post, let's redirect to it\n\n $url = get_the_permalink();\n wp_redirect( $url );\n exit;\n\n } else { // more than one post\n\n // normal loop stuff here\n\n }\n\n }\n\n} else {\n\n // Do this is there are no posts at all\n\n}\n</code></pre>\n" } ]
2020/02/04
[ "https://wordpress.stackexchange.com/questions/357864", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/164293/" ]
I'm trying to get a link from a custom post with a custom taxonomy but I'm running into issues trying to get it. I'm wanting to send the user straight to the post if the taxonomy count is 1. If it's greater than one post, it goes to a page showing all the posts of the taxonomy. I have this second part working, but I can't get the first bit to work, I can't get the taxonomy to return the post. ``` <?php $taxonomy = 'treatment_type'; $terms = get_terms($taxonomy); // Get all terms of a taxonomy //print_r($terms ); if ( $terms && !is_wp_error( $terms ) ) :?> <?php foreach ( $terms as $term ) { if('trending-treatment' !== $term->slug && 'skin-care' !== $term->slug){ ?> <?php if($term->count == 1){?> <?php $posts_array = get_posts( array( 'showposts' => -1, 'post_type' => 'treatment', 'tax_query' => array( array( 'taxonomy' => 'treatment_type', 'field' => 'term_id', 'terms' => $term->slug, ) ) ) ); print_r( $posts_array ); ?> <h1>only 1</h1> <?php print_r($term); ?> <article class="portfolio-item pf-rejuv"> <div class="portfolio-image"> <a href="POST LINK TO GO HERE"> <img src="<?php the_field('image', $term); ?>" alt="<?php echo $term->name; ?>"> </a> </div> <div class="portfolio-desc"> <div class="team-title"><h4><?php echo $term->name; ?></h4><span> <?php the_field('types_of_treatments', $term); ?></span></div> </div> </article> <?php }else{ ?> <article class="portfolio-item pf-rejuv"> <div class="portfolio-image"> <a href="<?php echo get_term_link($term->slug, $taxonomy); ?>"> <img src="<?php the_field('image', $term); ?>" alt="<?php echo $term->name; ?>"> </a> </div> <div class="portfolio-desc"> <div class="team-title"><h4><?php echo $term->name; ?></h4><span> <?php the_field('types_of_treatments', $term); ?></span></div> </div> </article> <?php } ?> <?php } } ?> <?php endif;?> ```
> > I can't get the first bit to work, I can't get the taxonomy to return > the post. > > > So the following is the first bit which queries posts in a single taxonomy term: ```php $posts_array = get_posts( array( 'showposts' => -1, 'post_type' => 'treatment', 'tax_query' => array( array( 'taxonomy' => 'treatment_type', 'field' => 'term_id', 'terms' => $term->slug, ) ) ) ); ``` And the problem there is that the `tax_query`'s `field` and `terms` values don't match — you set the `field` to `term_id` (term ID), but then the `terms` is a term slug and not ID. So make sure they match: * Change the `'field' => 'term_id'` to `'field' => 'slug'`. * Or change the `'terms' => $term->slug` to `'terms' => $term->term_id`. And actually, you should use the parameter `numberposts` or better `posts_per_page` and not `showposts` (which is *not* a standard parameter for `get_posts()` or `WP_Query`).
357,948
<p>Is it possible to edit order item totals and custom fees in the woocommerce admin edit order screen? The only hook that I can find is <code>woocommerce_new_order_item</code>, but when I add/remove a product in the admin I need to adjust the custom order items totals (e.g. like deposit and delivery fees which are order line item fees).</p> <p>For example, if I increase the quantity of a product (or add a different product to the order) in the edit order admin, I need to also increase the deposit amount on the order. I would also need to do the opposite, if I decrease quantity or remove a product from the order I'll need to decrease the deposit amount. </p> <p>Is this doable?? What hooks should I be looking at? I've searched several forums and can't seem to find an answer.</p> <p>Any help at all would be greatly appreciated.</p>
[ { "answer_id": 357964, "author": "Yashar", "author_id": 146615, "author_profile": "https://wordpress.stackexchange.com/users/146615", "pm_score": -1, "selected": false, "text": "<p>First of all, welcome to the community :)</p>\n<p>When you add/remove an order item (e.g a product), WooCommerce uses an Ajax call to update the order.</p>\n<h2>Adding a New Item to the Order</h2>\n<p>Adding a new item, would be done by <code>WC_AJAX::add_order_item()</code>. This method does the adding process and then fires <a href=\"https://docs.woocommerce.com/wc-apidocs/source-class-WC_AJAX.html#920\" rel=\"nofollow noreferrer\"><code>woocommerce_ajax_order_items_added</code></a> action hook. We can use that action to do some nasty stuff on the order!</p>\n<p>For an example, if I want to add an order fee with total of 1000, when a product from product category 188 is added to the order, this would do the trick:</p>\n<pre><code>add_action('woocommerce_ajax_order_items_added', 'tst_update_order', 10, 2);\n\n/**\n * @param \\WC_Order_Item[] $added_items\n * @param \\WC_order $order\n */\nfunction tst_update_order( $added_items, $order )\n{\n foreach ( $added_items as $added_item ) {\n\n if ( 'line_item' === $added_item-&gt;get_type() ) {\n\n /** @var \\WC_Order_Item_Product $added_item */\n $product = $added_item-&gt;get_product();\n $cat_ids = $product-&gt;get_category_ids();\n\n if ( in_array( 188, $cat_ids ) ) {\n $fee = new \\WC_Order_Item_Fee();\n $fee-&gt;set_name('Order Fee');\n $fee-&gt;set_total('1000');\n $fee-&gt;save();\n $order-&gt;add_item($fee);\n $order-&gt;save();\n }\n }\n }\n}\n</code></pre>\n<p><strong>Note:</strong> There is another action <a href=\"https://docs.woocommerce.com/wc-apidocs/source-class-WC_AJAX.html#914\" rel=\"nofollow noreferrer\"><code>woocommerce_ajax_add_order_item_meta</code></a> which fires on updating every single order item. You may want to use that instead of looping through <code>$added_items</code>.</p>\n<h2>Removing an existing Item from the Order</h2>\n<p>The corresponding method for removing an item from the current order is <code>WC_AJAX::remove_order_item()</code>. this method itself uses <code>wc_delete_order_item()</code> function to remove an order item. You may want to use the <a href=\"https://docs.woocommerce.com/wc-apidocs/source-class-Abstract_WC_Order_Item_Type_Data_Store.html#101\" rel=\"nofollow noreferrer\"><code>woocommerce_before_delete_order_item</code></a> action which is defined in this function to do your calculations and update the order.</p>\n" }, { "answer_id": 358323, "author": "kojak", "author_id": 66596, "author_profile": "https://wordpress.stackexchange.com/users/66596", "pm_score": 1, "selected": true, "text": "<p>The <code>woocommerce_order_before_calculate_totals</code> hook executes in the Edit Order admin screen when an item is changed or the 'recalculate' button is pressed. This allows you to loop through each item and fee in the order and edit as required. I have a fee called 'Deposit' which I update if it exists or I add if it doesn't.</p>\n\n<pre><code>function custom_order_before_calculate_totals($and_taxes, $order ) {\n // The loop to get the order items which are WC_Order_Item_Product objects since WC 3+\n // loop all products and calculate total deposit\n $total_deposit = 0;\n foreach( $order-&gt;get_items() as $item_id =&gt; $item ) {\n // get the WC_Product object\n $product = $item-&gt;get_product();\n\n // get the quantity\n $product_quantity = $item-&gt;get_quantity();\n\n // get the deposit amount\n $deposit = $product-&gt;get_attribute('deposit') * $product_quantity;\n\n // sum of deposits from all products\n $total_deposit += $deposit;\n }\n\n\n // update the Deposit fee if it exists\n $deposit_fee_exists = false;\n foreach( $order-&gt;get_fees() as $item_id =&gt; $item_fee ) {\n $fee_name = $item_fee-&gt;get_name();\n\n if ( $fee_name == 'Deposit' ) {\n $item_fee-&gt;set_tax_status('none'); // no tax on deposit\n $item_fee-&gt;set_total($total_deposit);\n $deposit_fee_exists = true;\n break;\n }\n }\n\n // if there isn't an existing deposit fee then add it\n if ( $total_deposit &gt; 0 &amp;&amp; !$deposit_fee_exists ) {\n // Get a new instance of the WC_Order_Item_Fee Object\n $item_fee = new WC_Order_Item_Fee();\n\n $item_fee-&gt;set_name( \"Deposit\" ); // Generic fee name\n $item_fee-&gt;set_amount( $total_deposit ); // Fee amount\n $item_fee-&gt;set_tax_status( 'none' ); // or 'none'\n $item_fee-&gt;set_total( $total_deposit ); // Fee amount\n\n // Add Fee item to the order\n $order-&gt;add_item( $item_fee );\n }\n}\nadd_action( 'woocommerce_order_before_calculate_totals', \"custom_order_before_calculate_totals\", 10, 3);\n</code></pre>\n" } ]
2020/02/05
[ "https://wordpress.stackexchange.com/questions/357948", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66596/" ]
Is it possible to edit order item totals and custom fees in the woocommerce admin edit order screen? The only hook that I can find is `woocommerce_new_order_item`, but when I add/remove a product in the admin I need to adjust the custom order items totals (e.g. like deposit and delivery fees which are order line item fees). For example, if I increase the quantity of a product (or add a different product to the order) in the edit order admin, I need to also increase the deposit amount on the order. I would also need to do the opposite, if I decrease quantity or remove a product from the order I'll need to decrease the deposit amount. Is this doable?? What hooks should I be looking at? I've searched several forums and can't seem to find an answer. Any help at all would be greatly appreciated.
The `woocommerce_order_before_calculate_totals` hook executes in the Edit Order admin screen when an item is changed or the 'recalculate' button is pressed. This allows you to loop through each item and fee in the order and edit as required. I have a fee called 'Deposit' which I update if it exists or I add if it doesn't. ``` function custom_order_before_calculate_totals($and_taxes, $order ) { // The loop to get the order items which are WC_Order_Item_Product objects since WC 3+ // loop all products and calculate total deposit $total_deposit = 0; foreach( $order->get_items() as $item_id => $item ) { // get the WC_Product object $product = $item->get_product(); // get the quantity $product_quantity = $item->get_quantity(); // get the deposit amount $deposit = $product->get_attribute('deposit') * $product_quantity; // sum of deposits from all products $total_deposit += $deposit; } // update the Deposit fee if it exists $deposit_fee_exists = false; foreach( $order->get_fees() as $item_id => $item_fee ) { $fee_name = $item_fee->get_name(); if ( $fee_name == 'Deposit' ) { $item_fee->set_tax_status('none'); // no tax on deposit $item_fee->set_total($total_deposit); $deposit_fee_exists = true; break; } } // if there isn't an existing deposit fee then add it if ( $total_deposit > 0 && !$deposit_fee_exists ) { // Get a new instance of the WC_Order_Item_Fee Object $item_fee = new WC_Order_Item_Fee(); $item_fee->set_name( "Deposit" ); // Generic fee name $item_fee->set_amount( $total_deposit ); // Fee amount $item_fee->set_tax_status( 'none' ); // or 'none' $item_fee->set_total( $total_deposit ); // Fee amount // Add Fee item to the order $order->add_item( $item_fee ); } } add_action( 'woocommerce_order_before_calculate_totals', "custom_order_before_calculate_totals", 10, 3); ```
357,962
<p>I have tried this code, but it doesn't work.</p> <pre class="lang-php prettyprint-override"><code>function university_adjust_queries($query) { $query-&gt;set('post_per_page', '1'); } add_action('pre_get_posts', 'university_adjust_queries'); </code></pre>
[ { "answer_id": 357965, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": false, "text": "<p>You're missing an s.</p>\n\n<p><code>$query-&gt;set('posts_per_page', '1');</code></p>\n\n<p>However - you probably don't want to do this for every query, since that affects everything - widgets, back end, everything. You should make it conditional. For example:</p>\n\n<pre><code>&lt;?php\nfunction university_adjust_queries($query) {\n // If this is the main query, not in wp-admin, and this is the homepage\n if($query-&gt;is_main_query() &amp;&amp; !is_admin() &amp;&amp; $query-&gt;is_home()) {\n $query-&gt;set('posts_per_page', '1');\n }\n}\nadd_action('pre_get_posts', 'university_adjust_queries');\n?&gt;\n</code></pre>\n\n<p>This will make sure you're only affecting the main query (The Loop) on the homepage, and only on the front end. You can adjust the condition to target whichever spot you're wanting to affect.</p>\n" }, { "answer_id": 358049, "author": "Chris", "author_id": 182221, "author_profile": "https://wordpress.stackexchange.com/users/182221", "pm_score": 0, "selected": false, "text": "<pre><code>function university_adjust_queries($query) {\n if (!is_admin() AND is_post_type_archive('event') AND $query-&gt;is_main_query()) {\n $query-&gt;set('posts_per_page', 1);\n}\n</code></pre>\n" } ]
2020/02/05
[ "https://wordpress.stackexchange.com/questions/357962", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/182221/" ]
I have tried this code, but it doesn't work. ```php function university_adjust_queries($query) { $query->set('post_per_page', '1'); } add_action('pre_get_posts', 'university_adjust_queries'); ```
You're missing an s. `$query->set('posts_per_page', '1');` However - you probably don't want to do this for every query, since that affects everything - widgets, back end, everything. You should make it conditional. For example: ``` <?php function university_adjust_queries($query) { // If this is the main query, not in wp-admin, and this is the homepage if($query->is_main_query() && !is_admin() && $query->is_home()) { $query->set('posts_per_page', '1'); } } add_action('pre_get_posts', 'university_adjust_queries'); ?> ``` This will make sure you're only affecting the main query (The Loop) on the homepage, and only on the front end. You can adjust the condition to target whichever spot you're wanting to affect.
357,992
<p>I have a function to obtain specific taxonomies in each entry. The problem is, for each entry, it shows all the values that the taxonomy contains. How can I do to show the correct value to each entry? I don't know about programming. I appreciate you being clear in the answer. Thank you</p> <pre><code> $terms = get_terms( ( array('taxonomy' =&gt; 'dormitorio', 'hide_empty' =&gt; false,))); if ( isset( $terms ) &amp;&amp; '' !== $terms ) { foreach( $terms as $term ) { echo '&lt;div class="tax dormitorio ' . $term-&gt;slug . '"&gt;'; echo $term-&gt;name; echo '&lt;/div&gt;'; } </code></pre>
[ { "answer_id": 357965, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": false, "text": "<p>You're missing an s.</p>\n\n<p><code>$query-&gt;set('posts_per_page', '1');</code></p>\n\n<p>However - you probably don't want to do this for every query, since that affects everything - widgets, back end, everything. You should make it conditional. For example:</p>\n\n<pre><code>&lt;?php\nfunction university_adjust_queries($query) {\n // If this is the main query, not in wp-admin, and this is the homepage\n if($query-&gt;is_main_query() &amp;&amp; !is_admin() &amp;&amp; $query-&gt;is_home()) {\n $query-&gt;set('posts_per_page', '1');\n }\n}\nadd_action('pre_get_posts', 'university_adjust_queries');\n?&gt;\n</code></pre>\n\n<p>This will make sure you're only affecting the main query (The Loop) on the homepage, and only on the front end. You can adjust the condition to target whichever spot you're wanting to affect.</p>\n" }, { "answer_id": 358049, "author": "Chris", "author_id": 182221, "author_profile": "https://wordpress.stackexchange.com/users/182221", "pm_score": 0, "selected": false, "text": "<pre><code>function university_adjust_queries($query) {\n if (!is_admin() AND is_post_type_archive('event') AND $query-&gt;is_main_query()) {\n $query-&gt;set('posts_per_page', 1);\n}\n</code></pre>\n" } ]
2020/02/06
[ "https://wordpress.stackexchange.com/questions/357992", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/182248/" ]
I have a function to obtain specific taxonomies in each entry. The problem is, for each entry, it shows all the values that the taxonomy contains. How can I do to show the correct value to each entry? I don't know about programming. I appreciate you being clear in the answer. Thank you ``` $terms = get_terms( ( array('taxonomy' => 'dormitorio', 'hide_empty' => false,))); if ( isset( $terms ) && '' !== $terms ) { foreach( $terms as $term ) { echo '<div class="tax dormitorio ' . $term->slug . '">'; echo $term->name; echo '</div>'; } ```
You're missing an s. `$query->set('posts_per_page', '1');` However - you probably don't want to do this for every query, since that affects everything - widgets, back end, everything. You should make it conditional. For example: ``` <?php function university_adjust_queries($query) { // If this is the main query, not in wp-admin, and this is the homepage if($query->is_main_query() && !is_admin() && $query->is_home()) { $query->set('posts_per_page', '1'); } } add_action('pre_get_posts', 'university_adjust_queries'); ?> ``` This will make sure you're only affecting the main query (The Loop) on the homepage, and only on the front end. You can adjust the condition to target whichever spot you're wanting to affect.
358,004
<p>i need to get a list of all updates the wp site need (core, plugin and themes). i already know about wp_get_update_data(), but it give me back only the number. i need to get for example:</p> <blockquote> <p>plugin1 | actual version | new version</p> <p>plugin2 | actual version | new version</p> <p>theme1 | actual version | new version</p> <p>wp | actual version | new version</p> </blockquote> <p>how can i save that information into some arrays to use them? </p> <p>edit: i managed to do this with what i found but it doesn't work, it print to try only test</p> <pre><code>function data_report() { // Get theme info $theme_data = wp_get_theme(); $theme = $theme_data-&gt;Name . ' ' . $theme_data-&gt;Version; // Get plugins that have an update $updates = get_plugin_updates(); // WordPress active plugins $fin_plug = "\n" . '-- WordPress Active Plugins' . "\n\n"; $plugins = get_plugins(); $active_plugins = get_option('active_plugins', array()); foreach ($plugins as $plugin_path =&gt; $plugin) { if (!in_array($plugin_path, $active_plugins)) { continue; } $update = array_key_exists($plugin_path, $updates) ? ' (needs update - ' . $updates[$plugin_path]-&gt;update-&gt;new_version . ')' : ''; $fin_plug .= $plugin['Name'] . ': ' . $plugin['Version'] . $update . "\n"; } } add_action( 'wp_footer', 'stampa_prova' ); function stampa_prova (){ echo 'test'; $cospi = data_report(); echo $cospi; } </code></pre>
[ { "answer_id": 358006, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": false, "text": "<p>When on the admin view you can use the following functions to get update data.</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/get_plugin_updates/\" rel=\"nofollow noreferrer\">get_plugin_updates()</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/get_theme_updates/\" rel=\"nofollow noreferrer\">get_theme_updates()</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/get_core_updates/\" rel=\"nofollow noreferrer\">get_core_updates()</a></li>\n</ul>\n\n<p>If you want to build your own functions, then you can get update related data from site transients <code>update_themes</code>, <code>update_plugins</code>, and <code>update_core</code>. Then you can compare the plugin and theme transients with the theme and plugin arrays you can get with <a href=\"https://developer.wordpress.org/reference/functions/wp_get_themes/\" rel=\"nofollow noreferrer\">wp_get_themes()</a> and <a href=\"https://developer.wordpress.org/reference/functions/get_plugins/\" rel=\"nofollow noreferrer\">get_plugins()</a>. The above functions are more or less wrappers for these transients and functions.</p>\n\n<p>Have a look at the source for the functions to see how WP handles this stuff.</p>\n" }, { "answer_id": 358086, "author": "DevBeppe", "author_id": 182053, "author_profile": "https://wordpress.stackexchange.com/users/182053", "pm_score": 0, "selected": false, "text": "<p>solved, if someone need the code i posted work, need only to add the admin permission to execute with <code>require_once</code></p>\n" }, { "answer_id": 382163, "author": "Gendrith", "author_id": 162581, "author_profile": "https://wordpress.stackexchange.com/users/162581", "pm_score": 2, "selected": false, "text": "<p>The answer made by Antti Koskinen is great. It helped me to make a function to get the plugins info for a custom API endpoint, I hope it can help somebody else</p>\n<pre><code> function system_check() {\n if (!function_exists('get_plugins')) {\n require_once ABSPATH . 'wp-admin/includes/plugin.php';\n }\n if (!function_exists('get_site_transient')) {\n require_once ABSPATH . 'wp-admin/includes/option.php';\n }\n $updates = get_site_transient('update_plugins');\n $plugins = get_plugins();\n $the_list = array();\n $i = 1;\n if ($updates-&gt;response) {\n $the_list[&quot;ultima_revision&quot;] = date(&quot;Y-m-d g:i A&quot;, intval($updates-&gt;last_checked));\n foreach ($plugins as $name =&gt; $plugin) {\n $the_list[&quot;plugins&quot;][$i][&quot;id&quot;] = $name;\n $the_list[&quot;plugins&quot;][$i][&quot;name&quot;] = $plugin[&quot;Name&quot;];\n $the_list[&quot;plugins&quot;][$i][&quot;current_version&quot;] = $plugin[&quot;Version&quot;];\n if (isset($updates-&gt;response[$name])) {\n $the_list[&quot;plugins&quot;][$i][&quot;update&quot;] = &quot;yes&quot;;\n $the_list[&quot;plugins&quot;][$i][&quot;version&quot;] = $updates-&gt;response[$name]-&gt;new_version;\n } else {\n $the_list[&quot;plugins&quot;][$i][&quot;update&quot;] = &quot;no&quot;;\n }\n $i++;\n }\n }\n return $the_list;\n }\n</code></pre>\n" } ]
2020/02/06
[ "https://wordpress.stackexchange.com/questions/358004", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/182053/" ]
i need to get a list of all updates the wp site need (core, plugin and themes). i already know about wp\_get\_update\_data(), but it give me back only the number. i need to get for example: > > plugin1 | actual version | new version > > > plugin2 | actual version | new version > > > theme1 | actual version | new version > > > wp | actual version | new version > > > how can i save that information into some arrays to use them? edit: i managed to do this with what i found but it doesn't work, it print to try only test ``` function data_report() { // Get theme info $theme_data = wp_get_theme(); $theme = $theme_data->Name . ' ' . $theme_data->Version; // Get plugins that have an update $updates = get_plugin_updates(); // WordPress active plugins $fin_plug = "\n" . '-- WordPress Active Plugins' . "\n\n"; $plugins = get_plugins(); $active_plugins = get_option('active_plugins', array()); foreach ($plugins as $plugin_path => $plugin) { if (!in_array($plugin_path, $active_plugins)) { continue; } $update = array_key_exists($plugin_path, $updates) ? ' (needs update - ' . $updates[$plugin_path]->update->new_version . ')' : ''; $fin_plug .= $plugin['Name'] . ': ' . $plugin['Version'] . $update . "\n"; } } add_action( 'wp_footer', 'stampa_prova' ); function stampa_prova (){ echo 'test'; $cospi = data_report(); echo $cospi; } ```
When on the admin view you can use the following functions to get update data. * [get\_plugin\_updates()](https://developer.wordpress.org/reference/functions/get_plugin_updates/) * [get\_theme\_updates()](https://developer.wordpress.org/reference/functions/get_theme_updates/) * [get\_core\_updates()](https://developer.wordpress.org/reference/functions/get_core_updates/) If you want to build your own functions, then you can get update related data from site transients `update_themes`, `update_plugins`, and `update_core`. Then you can compare the plugin and theme transients with the theme and plugin arrays you can get with [wp\_get\_themes()](https://developer.wordpress.org/reference/functions/wp_get_themes/) and [get\_plugins()](https://developer.wordpress.org/reference/functions/get_plugins/). The above functions are more or less wrappers for these transients and functions. Have a look at the source for the functions to see how WP handles this stuff.
358,031
<p>So Yoast SEO has an issue where you can't define a global default twitter card image.</p> <p>So I'm looking to both set a default twitter card image but allow for the override on the specific pages to actually work.</p> <p>I'm currently using:</p> <pre><code>$default_opengraph = 'https://website.com/image.png'; function default_opengraph() { global $default_opengraph; return $default_opengraph; } add_filter('wpseo_twitter_image','default_opengraph'); </code></pre> <p>Which allows me to globally set the default twitter card image, but the problem with this is:</p> <ol> <li>It prevents page specific overrides from working (Yoast SEO Customs / Featured Image)</li> <li>It needs to be manually defined.</li> </ol> <p>Anyone able to help find a fix for this, it's something YoastSEO itself should have in the plugin and they have loads of requests on WordPress forums, github as well as on their site asking for this and they've been asking for several years but they still haven't added it...</p> <p>Hopefully someone can help with this as it's largely applicable and useful for many many users.</p> <p>Thanks</p>
[ { "answer_id": 358061, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 0, "selected": false, "text": "<p>If there is already an image set then it is <a href=\"https://github.com/Yoast/wordpress-seo/blob/13.0/frontend/class-twitter.php#L518\" rel=\"nofollow noreferrer\">passed to the wpseo_twitter_image filter when it's called</a> as a parameter:</p>\n\n<pre><code>/**\n * Filter: 'wpseo_twitter_image' - Allow changing the Twitter Card image.\n *\n * @api string $img Image URL string.\n */\n$img = apply_filters( 'wpseo_twitter_image', $img );\n</code></pre>\n\n<p>so you can easily fix your filter so that it won't overwrite an existing value, e.g.</p>\n\n<pre><code>$default_opengraph = 'https://website.com/image.png';\nfunction default_opengraph( $img ) {\n if ( is_string( $img ) &amp;&amp; ( $img !== '' ) ) {\n // We have a value set\n return $img;\n }\n\n // No image: return the default\n global $default_opengraph;\n return $default_opengraph;\n}\nadd_filter( 'wpseo_twitter_image','default_opengraph' );\n</code></pre>\n\n<p>However at first glance there is a default image option, og_default_image, which is serialised into the wp_options value wpseo_social. I don't know if / where you can configure this in the admin site though.</p>\n" }, { "answer_id": 372561, "author": "Stefan Vetter", "author_id": 192798, "author_profile": "https://wordpress.stackexchange.com/users/192798", "pm_score": 2, "selected": false, "text": "<p>Here's how I fixed it. If you paste this code in your theme's functions.php, it will use the image set for Facebook also for Twitter if no image is set for Twitter.</p>\n<p>If there is not image set for both Facebook and Twitter, it falls back to the default Facebook image in the Yoast settings (unfortunately, you can't provide a default Twitter image there, so we'll be using the Facebook one).</p>\n<pre><code> // Add Twitter image to every page /article if none is defined\n\nadd_filter('wpseo_twitter_image', 'change_twitter_image');\n\nfunction change_twitter_image($image) {\n\n if (!$image) {\n\n global $post;\n \n if (!$image = get_post_meta($post-&gt;ID)[&quot;_yoast_wpseo_opengraph-image&quot;][0]) {\n $image = get_option(&quot;wpseo_social&quot;)[&quot;og_default_image&quot;];\n }\n\n }\n \n return $image; \n \n}; \n</code></pre>\n" } ]
2020/02/06
[ "https://wordpress.stackexchange.com/questions/358031", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91245/" ]
So Yoast SEO has an issue where you can't define a global default twitter card image. So I'm looking to both set a default twitter card image but allow for the override on the specific pages to actually work. I'm currently using: ``` $default_opengraph = 'https://website.com/image.png'; function default_opengraph() { global $default_opengraph; return $default_opengraph; } add_filter('wpseo_twitter_image','default_opengraph'); ``` Which allows me to globally set the default twitter card image, but the problem with this is: 1. It prevents page specific overrides from working (Yoast SEO Customs / Featured Image) 2. It needs to be manually defined. Anyone able to help find a fix for this, it's something YoastSEO itself should have in the plugin and they have loads of requests on WordPress forums, github as well as on their site asking for this and they've been asking for several years but they still haven't added it... Hopefully someone can help with this as it's largely applicable and useful for many many users. Thanks
Here's how I fixed it. If you paste this code in your theme's functions.php, it will use the image set for Facebook also for Twitter if no image is set for Twitter. If there is not image set for both Facebook and Twitter, it falls back to the default Facebook image in the Yoast settings (unfortunately, you can't provide a default Twitter image there, so we'll be using the Facebook one). ``` // Add Twitter image to every page /article if none is defined add_filter('wpseo_twitter_image', 'change_twitter_image'); function change_twitter_image($image) { if (!$image) { global $post; if (!$image = get_post_meta($post->ID)["_yoast_wpseo_opengraph-image"][0]) { $image = get_option("wpseo_social")["og_default_image"]; } } return $image; }; ```
358,037
<p>I’d like to generate images suitable to insert into metadata (like Open Graph or twitter:image). Basically I want to create a collage based on posts for each tag. So let’s say I had the tag “cats” which had 30 posts, 10 of which had a “featured image” of cats in them.</p> <p>If someone shares <a href="http://example.org/tag/cats" rel="nofollow noreferrer">http://example.org/tag/cats</a> to twitter I want to add metadata to point to a 1024x512 image that is a collage of some of those featured images. And ideally this is am image that would update at some period, so in a year when I have 10 more available images it’s kept up to date.</p> <p><strong>Questions:</strong></p> <ol> <li>Do plugins to aggregate featured images exist in this way?</li> <li>Are there native WordPress functions to manipulate images, or plugins to add this functionality?</li> <li>I want to keep such images up to date, how do I do this without bogging down load on my server?</li> <li>Is saving these images into the default uploads folder even a good idea? Will there be pitfalls if I am changing these images on the fly if I am also using a CDN?</li> </ol>
[ { "answer_id": 358178, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Are there native WordPress functions to manipulate images</p>\n</blockquote>\n\n<p>Yes, there's is the <a href=\"https://developer.wordpress.org/reference/classes/wp_image_editor/\" rel=\"nofollow noreferrer\">WP_Image_Editor</a> class for manipulating images. But I don't think it is able to combine images. Unless the <a href=\"https://developer.wordpress.org/reference/classes/wp_image_editor_gd/\" rel=\"nofollow noreferrer\">WP_Image_Editor_GD</a> or <a href=\"https://developer.wordpress.org/reference/classes/wp_image_editor_imagick/\" rel=\"nofollow noreferrer\">WP_Image_Editor_Imagick</a> subclasses support that somehow.</p>\n\n<p>You can use WP to query the posts in tag and get the featured images. Then use plain PHP to combine the images into a collage. E.g. <a href=\"https://stackoverflow.com/questions/10397842/php-create-one-image-from-images\">https://stackoverflow.com/questions/10397842/php-create-one-image-from-images</a></p>\n\n<blockquote>\n <p>I want to keep such images up to date, how do I do this without bogging down load on my server?</p>\n</blockquote>\n\n<p>You could use <a href=\"https://developer.wordpress.org/plugins/cron/\" rel=\"nofollow noreferrer\">WP Cron</a> with (daily) schedule as @kero suggested to update the og image. Another way could be to hook custom function <code>save_post</code> action and update the image when a new post is published and has tag(s) and a featured image set.</p>\n\n<p>With cron you may want to disable the default WP cron and schedule a real cronjob on your server so that the image update function runs even when there are no visitors on your site.</p>\n" }, { "answer_id": 358237, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>Ignoring our off-topic request for a plugin, the good news is: yes, this is possible. On the other hand, it is quite some work, so I will give just an outline here.</p>\n\n<p>WordPress does have built-in image manipulation. The default one is <a href=\"https://developer.wordpress.org/reference/classes/wp_image_editor_imagick/\" rel=\"nofollow noreferrer\">Image Magick</a>. WordPress' image editor class, however, only offers a subset of what Image Magick is actually capable of. This means that you will have to pierce through the class and use the <a href=\"https://www.php.net/manual/en/book.imagick.php\" rel=\"nofollow noreferrer\"><code>PHP</code> commands</a> directly to do what you want.</p>\n\n<p>First you will have to register an image size</p>\n\n<pre><code>add_action( 'init', 'wpse358037_register_collage_size' ); \nfunction wpse358037_register_collage_size() {\n add_image_size( 'collage', 1024, 512, true ); \n }\n</code></pre>\n\n<p>Second, when a tag is created you want to set a featured image for it, composed from one or more featured images of posts with that tag. There are several ways to do this, but the handiest may be hooking into the <code>set_object_terms</code> action. This fires at the end of <a href=\"https://developer.wordpress.org/reference/functions/wp_set_object_terms/\" rel=\"nofollow noreferrer\"><code>wp_set_object_terms</code></a>, a function that is executed whenever a post taxonomy is created or updated. Assuming that you only want to update the collage image when a new post/picture has been added, this is the perfect hook to create/update the collage without putting a burden on your server. You create the collage image and attach it as metadata to the tag. Pseudocode:</p>\n\n<pre><code>add_action( 'set_object_terms', 'wpse358037_register_collage_size', 10, 6 );\nfunction wpse358037_register_collage_size ($object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids) {\n if (... some sort of condition to match only post tags ...) {\n // if there are multiple tags, you may have to loop throug them\n foreach ($tags as $tag) {\n $images_to_be_used = ... depending on tag and you criteria make array of images\n $collage_image_path = wpse358037_collage_image ($tag, $images_to_be_used);\n // save the path to the resulting image as metadata to the tag\n add_term_meta ($tag_ID, 'collage-image', $collage_image_path, false) ;\n }\n }\n }\n</code></pre>\n\n<p>Finally you'll have to do the actual image action for which Image Magick even has a native function called <a href=\"https://phpimagick.com/Imagick/mosaicImages\" rel=\"nofollow noreferrer\">mosaic</a>:</p>\n\n<pre><code> function wpse358037_collage_image ($tag, $images_to_be_used) {\n // loop through all $images_to_be_used doing this\n $collage_image[i] = new Imagick( $path_to_image);\n // now you have an array of images ready to be handled by Image Magick\n .. do your mosaic magic and save the result in $collage_image_final_result\n // all that is left now is saving the image and return the path so it can be saved as metadata\n $path = .. wherever you want to save it (upload_dir + name + '.jpg')\n $collage_image_final_result-&gt;writeImage ($path);\n return $path;\n }\n</code></pre>\n\n<p>As you can see, there's still quite a lot of development work to be done, but hopefully this outline will help you get what you want.</p>\n" } ]
2020/02/06
[ "https://wordpress.stackexchange.com/questions/358037", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/12/" ]
I’d like to generate images suitable to insert into metadata (like Open Graph or twitter:image). Basically I want to create a collage based on posts for each tag. So let’s say I had the tag “cats” which had 30 posts, 10 of which had a “featured image” of cats in them. If someone shares <http://example.org/tag/cats> to twitter I want to add metadata to point to a 1024x512 image that is a collage of some of those featured images. And ideally this is am image that would update at some period, so in a year when I have 10 more available images it’s kept up to date. **Questions:** 1. Do plugins to aggregate featured images exist in this way? 2. Are there native WordPress functions to manipulate images, or plugins to add this functionality? 3. I want to keep such images up to date, how do I do this without bogging down load on my server? 4. Is saving these images into the default uploads folder even a good idea? Will there be pitfalls if I am changing these images on the fly if I am also using a CDN?
Ignoring our off-topic request for a plugin, the good news is: yes, this is possible. On the other hand, it is quite some work, so I will give just an outline here. WordPress does have built-in image manipulation. The default one is [Image Magick](https://developer.wordpress.org/reference/classes/wp_image_editor_imagick/). WordPress' image editor class, however, only offers a subset of what Image Magick is actually capable of. This means that you will have to pierce through the class and use the [`PHP` commands](https://www.php.net/manual/en/book.imagick.php) directly to do what you want. First you will have to register an image size ``` add_action( 'init', 'wpse358037_register_collage_size' ); function wpse358037_register_collage_size() { add_image_size( 'collage', 1024, 512, true ); } ``` Second, when a tag is created you want to set a featured image for it, composed from one or more featured images of posts with that tag. There are several ways to do this, but the handiest may be hooking into the `set_object_terms` action. This fires at the end of [`wp_set_object_terms`](https://developer.wordpress.org/reference/functions/wp_set_object_terms/), a function that is executed whenever a post taxonomy is created or updated. Assuming that you only want to update the collage image when a new post/picture has been added, this is the perfect hook to create/update the collage without putting a burden on your server. You create the collage image and attach it as metadata to the tag. Pseudocode: ``` add_action( 'set_object_terms', 'wpse358037_register_collage_size', 10, 6 ); function wpse358037_register_collage_size ($object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids) { if (... some sort of condition to match only post tags ...) { // if there are multiple tags, you may have to loop throug them foreach ($tags as $tag) { $images_to_be_used = ... depending on tag and you criteria make array of images $collage_image_path = wpse358037_collage_image ($tag, $images_to_be_used); // save the path to the resulting image as metadata to the tag add_term_meta ($tag_ID, 'collage-image', $collage_image_path, false) ; } } } ``` Finally you'll have to do the actual image action for which Image Magick even has a native function called [mosaic](https://phpimagick.com/Imagick/mosaicImages): ``` function wpse358037_collage_image ($tag, $images_to_be_used) { // loop through all $images_to_be_used doing this $collage_image[i] = new Imagick( $path_to_image); // now you have an array of images ready to be handled by Image Magick .. do your mosaic magic and save the result in $collage_image_final_result // all that is left now is saving the image and return the path so it can be saved as metadata $path = .. wherever you want to save it (upload_dir + name + '.jpg') $collage_image_final_result->writeImage ($path); return $path; } ``` As you can see, there's still quite a lot of development work to be done, but hopefully this outline will help you get what you want.
358,046
<p>I created a block template and attached it to my cpt and I get this message on the post page neither of the two buttons or the two links in the vertical dot button work unless I disable <code>$pages_type_object-&gt;template_lock = 'all';</code></p> <p><a href="https://i.stack.imgur.com/eDHDB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eDHDB.png" alt="enter image description here"></a></p> <p>So how can I get rid of this message and keep the <code>$pages_type_object-&gt;template_lock = 'all';</code>?</p>
[ { "answer_id": 358135, "author": "Will", "author_id": 48698, "author_profile": "https://wordpress.stackexchange.com/users/48698", "pm_score": 0, "selected": false, "text": "<p>There sounds like there may be a couple issues going on. </p>\n\n<p>Regarding the message \"this block contains unexpected or invalid content\": \nThat message is occurs when the Gutenberg has noticed that the HTML that is to be generated (stored in the post_content column of your database) has changed in an unexpected. </p>\n\n<p><a href=\"https://github.com/WordPress/gutenberg/issues/7604\" rel=\"nofollow noreferrer\">This issue occurs very often and best practices of how block developers should avoid is not resolved.</a> </p>\n\n<p>Secondly, the <code>resolve</code> and the <code>convert to hotel</code> buttons should both respond to you when you click or select the button, by displaying an html block with your code. If you click or select either button and nothing happens, then there is possibly a bug with the Gutenberg editor or a bug with your custom post type code. It's hard to diagnose what could the issue be unless you share more code but as a start, I'd recommend installing the query-monitor plugin to see if there's any php errors as well as looking in for in your browser's web console (cntrl + shift + k). </p>\n" }, { "answer_id": 358320, "author": "bckelley", "author_id": 144783, "author_profile": "https://wordpress.stackexchange.com/users/144783", "pm_score": 2, "selected": true, "text": "<p>seems my problem was in my array</p>\n\n<pre><code>'level' =&gt; '3',\n</code></pre>\n\n<p>should've been</p>\n\n<pre><code>'level' =&gt; 3,\n</code></pre>\n" } ]
2020/02/06
[ "https://wordpress.stackexchange.com/questions/358046", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/144783/" ]
I created a block template and attached it to my cpt and I get this message on the post page neither of the two buttons or the two links in the vertical dot button work unless I disable `$pages_type_object->template_lock = 'all';` [![enter image description here](https://i.stack.imgur.com/eDHDB.png)](https://i.stack.imgur.com/eDHDB.png) So how can I get rid of this message and keep the `$pages_type_object->template_lock = 'all';`?
seems my problem was in my array ``` 'level' => '3', ``` should've been ``` 'level' => 3, ```
358,053
<p>I have taken over a site from someone. He has a list of businesses on the site, each one has a URL, saved as a field:</p> <p><code>$iframe_url = get_field(‘manufacturer_url’);</code></p> <p>It seems he used to manage this URL on a custom post-type page, but the actual field to edit the URL has disappeared – maybe in some recent WordPress update.</p> <p>I have made sure on the edit page, all the elements are checked off on the ‘screen options’ tab. But i still cannot see where this field is, where i can change the URL. Any ideas?</p> <p>Using Version 5.8.7 of the plugin WP version: WordPress 5.1.4 running Chameleon-Child theme.</p>
[ { "answer_id": 358135, "author": "Will", "author_id": 48698, "author_profile": "https://wordpress.stackexchange.com/users/48698", "pm_score": 0, "selected": false, "text": "<p>There sounds like there may be a couple issues going on. </p>\n\n<p>Regarding the message \"this block contains unexpected or invalid content\": \nThat message is occurs when the Gutenberg has noticed that the HTML that is to be generated (stored in the post_content column of your database) has changed in an unexpected. </p>\n\n<p><a href=\"https://github.com/WordPress/gutenberg/issues/7604\" rel=\"nofollow noreferrer\">This issue occurs very often and best practices of how block developers should avoid is not resolved.</a> </p>\n\n<p>Secondly, the <code>resolve</code> and the <code>convert to hotel</code> buttons should both respond to you when you click or select the button, by displaying an html block with your code. If you click or select either button and nothing happens, then there is possibly a bug with the Gutenberg editor or a bug with your custom post type code. It's hard to diagnose what could the issue be unless you share more code but as a start, I'd recommend installing the query-monitor plugin to see if there's any php errors as well as looking in for in your browser's web console (cntrl + shift + k). </p>\n" }, { "answer_id": 358320, "author": "bckelley", "author_id": 144783, "author_profile": "https://wordpress.stackexchange.com/users/144783", "pm_score": 2, "selected": true, "text": "<p>seems my problem was in my array</p>\n\n<pre><code>'level' =&gt; '3',\n</code></pre>\n\n<p>should've been</p>\n\n<pre><code>'level' =&gt; 3,\n</code></pre>\n" } ]
2020/02/06
[ "https://wordpress.stackexchange.com/questions/358053", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78146/" ]
I have taken over a site from someone. He has a list of businesses on the site, each one has a URL, saved as a field: `$iframe_url = get_field(‘manufacturer_url’);` It seems he used to manage this URL on a custom post-type page, but the actual field to edit the URL has disappeared – maybe in some recent WordPress update. I have made sure on the edit page, all the elements are checked off on the ‘screen options’ tab. But i still cannot see where this field is, where i can change the URL. Any ideas? Using Version 5.8.7 of the plugin WP version: WordPress 5.1.4 running Chameleon-Child theme.
seems my problem was in my array ``` 'level' => '3', ``` should've been ``` 'level' => 3, ```
358,091
<p>I have a custom post type created using the following code:</p> <pre><code>// Event Post type register_post_type('event', array( 'capability_type' =&gt; 'event', 'map_meta_cap' =&gt; true, 'supports' =&gt; array('title', 'editor', 'excerpt', 'revisions'), 'rewrite' =&gt; array('slug' =&gt; 'events'), 'has_archive' =&gt; true, 'public' =&gt; true, 'labels' =&gt; array( 'name' =&gt; 'Events', 'add_new_item' =&gt; 'Add new event', 'new_item' =&gt; 'New Event', 'edit_item' =&gt; 'Edit events', 'all_items' =&gt; 'All events', 'singular_name' =&gt; 'Event' ), 'menu_icon' =&gt; 'dashicons-calendar', 'taxonomies' =&gt; array( 'category' ) )); </code></pre> <p>I also have a member role called editor which gets all the capabilities (using Justin Tadlock's/Memberspress plugin):</p> <p><a href="https://i.stack.imgur.com/iHWw1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iHWw1.png" alt="capabilities"></a></p> <p>However, he cannot change the category of new or old event posts. I have found a weird workaround and it is to add the capability "Edit Posts" to that role, which is of course not a capability I wish him to have.</p> <p>I would love to understand what causes this issue and how to solve it. </p>
[ { "answer_id": 358098, "author": "user3135691", "author_id": 59755, "author_profile": "https://wordpress.stackexchange.com/users/59755", "pm_score": 0, "selected": false, "text": "<p>From what I can see on a first glance, you have a single-quote missing:</p>\n\n<pre><code>'name' =&gt; 'Events,\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>'name' =&gt; 'Events',\n</code></pre>\n\n<p>In addition, your declaration of the Custom Post Type is incomplete as far as I can see (and pretty ugly formatted).</p>\n\n<p>Try something like this:</p>\n\n<pre><code>&lt;?php\n\n/* Register Custom Post Type 'events' */\nfunction prefix_register_custom_post_type(){\n\n// Custom Post Type Name\n$cpt_name = 'events';\n// CPT Features/possible values:\n// 'title', 'editor', 'comments', 'revisions', 'trackbacks', 'author', 'excerpt', 'page-attributes', 'thumbnail', 'custom-fields', and 'post-formats'\n$cpt_features = array(\n 'title',\n 'revisions',\n 'thumbnail',\n 'editor'\n);\n// Slug\n$cpt_slug = 'events'; // What the URL will look like\n$labels = array(\n 'name' =&gt; __('Events', 'text-domain'),\n 'singular_name' =&gt; __('Event', 'text-domain'),\n 'menu_name' =&gt; __('Events', 'text-domain'),\n 'name_admin_bar' =&gt; __('Events', 'text-domain'),\n 'all_items' =&gt; __('All events', 'text-domain'), // Archive Page Name\n 'add_name' =&gt; __('Add new event', 'text-domain'),\n 'add_new_item' =&gt; __('Add new event', 'text-domain'),\n 'edit' =&gt; __('edit event', 'text-domain'),\n 'edit_item' =&gt; __('edit event', 'text-domain'),\n 'new_item' =&gt; __('New event', 'text-domain'),\n 'view' =&gt; __('View event', 'text-domain'),\n 'view_item' =&gt; __('View event', 'text-domain'),\n 'search_items' =&gt; __('Search ', 'text-domain'),\n 'parent' =&gt; __('Parent', 'text-domain'),\n 'not_found' =&gt; __('No events found', 'text-domain'),\n 'not_found_in_trash' =&gt; __('No events found in Trash', 'text-domain')\n);\n\n/* ------------------------------------------ End of Edit */\n$args = array(\n 'labels' =&gt; $labels,\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'exclude_from_search' =&gt; false,\n 'show_in_nav_menus' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'show_in_admin_bar' =&gt; true,\n 'menu_position' =&gt; 21,\n 'menu_icon' =&gt; 'dashicons-awards',\n 'can_export' =&gt; true,\n 'delete_with_user' =&gt; false,\n 'hierarchical' =&gt; true,\n 'has_archive' =&gt; true,\n 'query_var' =&gt; true,\n 'capability_type' =&gt; 'post',\n 'map_meta_cap' =&gt; true,\n // 'capabilities' =&gt; array(),\n 'rewrite' =&gt; array(\n 'slug' =&gt; $cpt_slug,\n 'with_front'=&gt; true,\n 'pages' =&gt; true,\n 'feeds' =&gt; false\n ),\n 'supports' =&gt; $cpt_features\n);\n\nregister_post_type($cpt_name, $args);\n\n}\nadd_action('init', 'prefix_register_custom_post_type');\n</code></pre>\n\n<p>Since this formatting is a bit easier to read, please check or replace your code with this and try again. This code usually allows \"editors\" to access and manipulate the registered custom post types. Also see the commented \"capabilities\" array where you can enter things like 'edit_posts'.</p>\n" }, { "answer_id": 358101, "author": "Vitauts Stočka", "author_id": 181289, "author_profile": "https://wordpress.stackexchange.com/users/181289", "pm_score": 1, "selected": false, "text": "<p>CPT capabilities do not cover taxonomies. Each taxonomy has its own capabilities. If you want to use default Categories, unfortunately you must give user \"Edit Posts\" capability. There is no easy way around it, especially with Gutenberg. Best solution would be to create custom taxonomy \"Event Categories\" with matching capability requirements, for example, mapping all taxonomy caps to \"edit_events\".</p>\n" } ]
2020/02/07
[ "https://wordpress.stackexchange.com/questions/358091", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168795/" ]
I have a custom post type created using the following code: ``` // Event Post type register_post_type('event', array( 'capability_type' => 'event', 'map_meta_cap' => true, 'supports' => array('title', 'editor', 'excerpt', 'revisions'), 'rewrite' => array('slug' => 'events'), 'has_archive' => true, 'public' => true, 'labels' => array( 'name' => 'Events', 'add_new_item' => 'Add new event', 'new_item' => 'New Event', 'edit_item' => 'Edit events', 'all_items' => 'All events', 'singular_name' => 'Event' ), 'menu_icon' => 'dashicons-calendar', 'taxonomies' => array( 'category' ) )); ``` I also have a member role called editor which gets all the capabilities (using Justin Tadlock's/Memberspress plugin): [![capabilities](https://i.stack.imgur.com/iHWw1.png)](https://i.stack.imgur.com/iHWw1.png) However, he cannot change the category of new or old event posts. I have found a weird workaround and it is to add the capability "Edit Posts" to that role, which is of course not a capability I wish him to have. I would love to understand what causes this issue and how to solve it.
CPT capabilities do not cover taxonomies. Each taxonomy has its own capabilities. If you want to use default Categories, unfortunately you must give user "Edit Posts" capability. There is no easy way around it, especially with Gutenberg. Best solution would be to create custom taxonomy "Event Categories" with matching capability requirements, for example, mapping all taxonomy caps to "edit\_events".
358,157
<p>I have a custom taxonomy (<code>video-category</code>) for a custom post type (<code>video</code>), and I'm trying to rewrite their paths in line with the examples below:</p> <p>Post (Archive): <code>about-us/video-center/category-name</code></p> <p>Post (Single): <code>about-us/video-center/category-name/post-title</code></p> <p>The post rewrite works as expected using: <code>'rewrite' =&gt; array( 'slug' =&gt; 'about-us/video-center/%category%', 'with_front' =&gt; false )</code></p> <p>However, the taxonomy page is giving me a 404 error with the following: <code>'rewrite' =&gt; array( 'slug' =&gt; 'about-us/video-center', 'with_front' =&gt; false );</code></p> <p>I realised that if I alter the rewrite path for the taxonomy to start with a page other than 'about-us', both redirects work. Unfortunately, I need both the archive and post pages to follow the exact same URL path.</p> <p>I've created a gist with the full registrations for both the CPT and taxonomy alongside a function which rewrites the <code>%category%</code> placeholder here: <a href="https://gist.github.com/graemebryson/92f5da5873a5edf0057d3b93b5cc4fdb" rel="nofollow noreferrer">https://gist.github.com/graemebryson/92f5da5873a5edf0057d3b93b5cc4fdb</a></p> <p>I've read most (if not all) related questions, but have been unable to find anything that allows both the taxonomy and post rewrites to share the same path. If it's not possible via rewrite, do I have any other options for forcing both to share the same URL path?</p>
[ { "answer_id": 358186, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<p><strong><em>(Revised on March 7<sup>th</sup> 2020 UTC)</em></strong></p>\n\n<p>So sharing the same permalink path (or <strong>rewrite slug/base</strong> as in <code>example.com/&lt;rewrite slug&gt;/&lt;term slug&gt;</code> and <code>example.com/&lt;rewrite slug&gt;/&lt;post slug&gt;</code>) is possible, and here's the (updated) code which enables you to share <strong>the exact same rewrite slug</strong> between a taxonomy and a post type:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function wpse_358157_parse_request( $wp ) {\n $path = 'about-us/video-center'; // rewrite slug; no trailing slashes\n $taxonomy = 'video-category'; // taxonomy slug\n $post_type = 'video'; // post type slug\n\n if ( preg_match( '#^' . preg_quote( $path, '#' ) . '/#', $wp-&gt;request ) &amp;&amp;\n isset( $wp-&gt;query_vars[ $taxonomy ] ) ) {\n $slug = $wp-&gt;query_vars[ $taxonomy ];\n $slug = ltrim( substr( $slug, strrpos( $slug, '/' ) ), '/' );\n\n if ( ! term_exists( $slug, $taxonomy ) ) {\n $wp-&gt;query_vars['name'] = $wp-&gt;query_vars[ $taxonomy ];\n $wp-&gt;query_vars['post_type'] = $post_type;\n $wp-&gt;query_vars[ $post_type ] = $wp-&gt;query_vars[ $taxonomy ];\n unset( $wp-&gt;query_vars[ $taxonomy ] );\n }\n }\n}\nadd_action( 'parse_request', 'wpse_358157_parse_request' );\n</code></pre>\n\n<h3>A brief explanation:</h3>\n\n<p>It's much easier to check if a term exists (than checking if a post exists) by the slug, so in the above code, we check if the current request satisfies a term request (i.e. the taxonomy query var — e.g. <code>video-category</code> — exists in the request and the request <em>path</em> matches the taxonomy's and post type's <em>rewrite slug</em>), and if so and that the term <strong>doesn't exist</strong>, then we <em>assume</em> it's a post request.</p>\n\n<p>I.e. We make WordPress treats the request as a request for a post <em>instead of</em> a term.</p>\n\n<h2>Additional Notes</h2>\n\n<ol>\n<li><p>Make sure your posts and terms do not share the <em>same slug</em>. Because the posts and terms share the same rewrite slug, so there would be no way to know whether we should load the post or the term.</p></li>\n<li><p>In the original answer, I mentioned that the taxonomy/term permalink can't be hierarchical (e.g. <code>example.com/&lt;rewrite slug&gt;/&lt;parent term slug&gt;/&lt;child term slug&gt;/</code>), but actually, it can be hierarchical! I just had no time to thoroughly test that before.. :)</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>register_taxonomy( 'video-category', 'video', [\n 'rewrite' =&gt; [\n 'slug' =&gt; 'about-us/video-center',\n 'with_front' =&gt; false,\n 'hierarchical' =&gt; true, // enable hierarchical term permalink\n ],\n 'hierarchical' =&gt; true,\n ...\n ]\n);\n</code></pre></li>\n<li><p>I also said that the post type needs to be registered before the taxonomy, but in my recent tests, it's actually the opposite — I registered the taxonomy first.</p>\n\n<p>So try to first register the taxonomy and then the post type. If that doesn't work, then register the post type first.</p></li>\n</ol>\n\n<h2>Full sample code</h2>\n\n<pre class=\"lang-php prettyprint-override\"><code>function my_register_taxonomy() {\n register_taxonomy( 'video-category', 'video', [\n 'rewrite' =&gt; [\n 'slug' =&gt; 'about-us/video-center',\n 'with_front' =&gt; false,\n 'hierarchical' =&gt; true,\n ],\n 'hierarchical' =&gt; true,\n 'labels' =&gt; [\n 'name' =&gt; 'Video Categories',\n 'singular_name' =&gt; 'Video Category',\n ],\n 'show_in_rest' =&gt; true,\n ]\n );\n}\n\nfunction my_register_post_type() {\n register_post_type( 'video', [\n 'rewrite' =&gt; [\n 'slug' =&gt; 'about-us/video-center',\n 'with_front' =&gt; false,\n ],\n 'has_archive' =&gt; 'about-us/video-center',\n 'hierarchical' =&gt; true,\n 'public' =&gt; true,\n 'supports' =&gt; [ 'title', 'editor', 'page-attributes' ],\n 'labels' =&gt; [\n 'name' =&gt; 'Videos',\n 'singular_name' =&gt; 'Video',\n ],\n 'show_in_rest' =&gt; true,\n ]\n );\n}\n\nadd_action( 'init', function () {\n my_register_taxonomy();\n my_register_post_type();\n\n /* If that doesn't work, you can try switching them:\n my_register_post_type();\n my_register_taxonomy();\n */\n} );\n\nfunction wpse_358157_parse_request( $wp ) {\n $path = 'about-us/video-center'; // rewrite slug; no trailing slashes\n $taxonomy = 'video-category'; // taxonomy slug\n $post_type = 'video'; // post type slug\n\n if ( preg_match( '#^' . preg_quote( $path, '#' ) . '/#', $wp-&gt;request ) &amp;&amp;\n isset( $wp-&gt;query_vars[ $taxonomy ] ) ) {\n $slug = $wp-&gt;query_vars[ $taxonomy ];\n $slug = ltrim( substr( $slug, strrpos( $slug, '/' ) ), '/' );\n\n if ( ! term_exists( $slug, $taxonomy ) ) {\n $wp-&gt;query_vars['name'] = $wp-&gt;query_vars[ $taxonomy ];\n $wp-&gt;query_vars['post_type'] = $post_type;\n $wp-&gt;query_vars[ $post_type ] = $wp-&gt;query_vars[ $taxonomy ];\n unset( $wp-&gt;query_vars[ $taxonomy ] );\n }\n }\n}\nadd_action( 'parse_request', 'wpse_358157_parse_request' );\n</code></pre>\n" }, { "answer_id": 412763, "author": "mircobabini", "author_id": 37607, "author_profile": "https://wordpress.stackexchange.com/users/37607", "pm_score": 0, "selected": false, "text": "<p><strong>Working solution for WooCommerce CPT <code>product</code> + Taxonomy <code>product_cat</code>.</strong></p>\n<p><strong>Setup</strong></p>\n<p>Change the Settings &gt; Permalinks structure to the same value for both the products base and the product category base.</p>\n<p><strong>Code</strong></p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse_358157_parse_request( $wp ) {\n // rewrite slug; no trailing slashes\n $path = trim( wc_get_permalink_structure()['product_base'], '/' );\n\n $taxonomy = 'product_cat'; // taxonomy slug\n $post_type = 'product'; // post type slug\n\n if ( preg_match( '#^' . preg_quote( $path, '#' ) . '/#', $wp-&gt;request ) &amp;&amp;\n isset( $wp-&gt;query_vars[ $taxonomy ] ) ) {\n $slug = $wp-&gt;query_vars[ $taxonomy ];\n $slug = ltrim( substr( $slug, strrpos( $slug, '/' ) ), '/' );\n\n if ( ! term_exists( $slug, $taxonomy ) ) {\n $wp-&gt;query_vars['name'] = $wp-&gt;query_vars[ $taxonomy ];\n $wp-&gt;query_vars['post_type'] = $post_type;\n $wp-&gt;query_vars[ $post_type ] = $wp-&gt;query_vars[ $taxonomy ];\n unset( $wp-&gt;query_vars[ $taxonomy ] );\n }\n }\n}\n\nadd_action( 'parse_request', 'wpse_358157_parse_request' );\n</code></pre>\n<p>Thanks @Sally CJ for the perfect generic solution.</p>\n" } ]
2020/02/07
[ "https://wordpress.stackexchange.com/questions/358157", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/163962/" ]
I have a custom taxonomy (`video-category`) for a custom post type (`video`), and I'm trying to rewrite their paths in line with the examples below: Post (Archive): `about-us/video-center/category-name` Post (Single): `about-us/video-center/category-name/post-title` The post rewrite works as expected using: `'rewrite' => array( 'slug' => 'about-us/video-center/%category%', 'with_front' => false )` However, the taxonomy page is giving me a 404 error with the following: `'rewrite' => array( 'slug' => 'about-us/video-center', 'with_front' => false );` I realised that if I alter the rewrite path for the taxonomy to start with a page other than 'about-us', both redirects work. Unfortunately, I need both the archive and post pages to follow the exact same URL path. I've created a gist with the full registrations for both the CPT and taxonomy alongside a function which rewrites the `%category%` placeholder here: <https://gist.github.com/graemebryson/92f5da5873a5edf0057d3b93b5cc4fdb> I've read most (if not all) related questions, but have been unable to find anything that allows both the taxonomy and post rewrites to share the same path. If it's not possible via rewrite, do I have any other options for forcing both to share the same URL path?
***(Revised on March 7th 2020 UTC)*** So sharing the same permalink path (or **rewrite slug/base** as in `example.com/<rewrite slug>/<term slug>` and `example.com/<rewrite slug>/<post slug>`) is possible, and here's the (updated) code which enables you to share **the exact same rewrite slug** between a taxonomy and a post type: ```php function wpse_358157_parse_request( $wp ) { $path = 'about-us/video-center'; // rewrite slug; no trailing slashes $taxonomy = 'video-category'; // taxonomy slug $post_type = 'video'; // post type slug if ( preg_match( '#^' . preg_quote( $path, '#' ) . '/#', $wp->request ) && isset( $wp->query_vars[ $taxonomy ] ) ) { $slug = $wp->query_vars[ $taxonomy ]; $slug = ltrim( substr( $slug, strrpos( $slug, '/' ) ), '/' ); if ( ! term_exists( $slug, $taxonomy ) ) { $wp->query_vars['name'] = $wp->query_vars[ $taxonomy ]; $wp->query_vars['post_type'] = $post_type; $wp->query_vars[ $post_type ] = $wp->query_vars[ $taxonomy ]; unset( $wp->query_vars[ $taxonomy ] ); } } } add_action( 'parse_request', 'wpse_358157_parse_request' ); ``` ### A brief explanation: It's much easier to check if a term exists (than checking if a post exists) by the slug, so in the above code, we check if the current request satisfies a term request (i.e. the taxonomy query var — e.g. `video-category` — exists in the request and the request *path* matches the taxonomy's and post type's *rewrite slug*), and if so and that the term **doesn't exist**, then we *assume* it's a post request. I.e. We make WordPress treats the request as a request for a post *instead of* a term. Additional Notes ---------------- 1. Make sure your posts and terms do not share the *same slug*. Because the posts and terms share the same rewrite slug, so there would be no way to know whether we should load the post or the term. 2. In the original answer, I mentioned that the taxonomy/term permalink can't be hierarchical (e.g. `example.com/<rewrite slug>/<parent term slug>/<child term slug>/`), but actually, it can be hierarchical! I just had no time to thoroughly test that before.. :) ```php register_taxonomy( 'video-category', 'video', [ 'rewrite' => [ 'slug' => 'about-us/video-center', 'with_front' => false, 'hierarchical' => true, // enable hierarchical term permalink ], 'hierarchical' => true, ... ] ); ``` 3. I also said that the post type needs to be registered before the taxonomy, but in my recent tests, it's actually the opposite — I registered the taxonomy first. So try to first register the taxonomy and then the post type. If that doesn't work, then register the post type first. Full sample code ---------------- ```php function my_register_taxonomy() { register_taxonomy( 'video-category', 'video', [ 'rewrite' => [ 'slug' => 'about-us/video-center', 'with_front' => false, 'hierarchical' => true, ], 'hierarchical' => true, 'labels' => [ 'name' => 'Video Categories', 'singular_name' => 'Video Category', ], 'show_in_rest' => true, ] ); } function my_register_post_type() { register_post_type( 'video', [ 'rewrite' => [ 'slug' => 'about-us/video-center', 'with_front' => false, ], 'has_archive' => 'about-us/video-center', 'hierarchical' => true, 'public' => true, 'supports' => [ 'title', 'editor', 'page-attributes' ], 'labels' => [ 'name' => 'Videos', 'singular_name' => 'Video', ], 'show_in_rest' => true, ] ); } add_action( 'init', function () { my_register_taxonomy(); my_register_post_type(); /* If that doesn't work, you can try switching them: my_register_post_type(); my_register_taxonomy(); */ } ); function wpse_358157_parse_request( $wp ) { $path = 'about-us/video-center'; // rewrite slug; no trailing slashes $taxonomy = 'video-category'; // taxonomy slug $post_type = 'video'; // post type slug if ( preg_match( '#^' . preg_quote( $path, '#' ) . '/#', $wp->request ) && isset( $wp->query_vars[ $taxonomy ] ) ) { $slug = $wp->query_vars[ $taxonomy ]; $slug = ltrim( substr( $slug, strrpos( $slug, '/' ) ), '/' ); if ( ! term_exists( $slug, $taxonomy ) ) { $wp->query_vars['name'] = $wp->query_vars[ $taxonomy ]; $wp->query_vars['post_type'] = $post_type; $wp->query_vars[ $post_type ] = $wp->query_vars[ $taxonomy ]; unset( $wp->query_vars[ $taxonomy ] ); } } } add_action( 'parse_request', 'wpse_358157_parse_request' ); ```
358,214
<p>I want to hide page menu from the admin panel for a specific user type. I tried it with the below codes in </p> <p><code>functions.php</code></p> <pre><code>function hide_menu_items() { global $menu; global $current_user; get_currentuserinfo(); if( $current_user-&gt;user_login == 'username' ): remove_menu_page( 'admin.php?page=megamenu' ); remove_menu_page( 'admin.php?page=mycustompage' ); endif; } add_action( 'admin_menu', 'hide_menu_items' ); </code></pre> <p>It's not working but it only hides post_types</p>
[ { "answer_id": 358193, "author": "Pavel Janicek", "author_id": 10575, "author_profile": "https://wordpress.stackexchange.com/users/10575", "pm_score": 1, "selected": false, "text": "<p>Surprisingly, for plugin development, correct answer is <strong>none</strong></p>\n\n<p>From <a href=\"https://developer.wordpress.org/reference/functions/wp_set_password/\" rel=\"nofollow noreferrer\">set password documentation</a>:</p>\n\n<pre><code>wp_set_password( string $password, int $user_id )\n</code></pre>\n\n<blockquote>\n <p>Updates the user’s password with a new encrypted one.</p>\n</blockquote>\n\n<p>If you think about security, try going with <a href=\"https://developer.wordpress.org/reference/functions/wp_generate_password/\" rel=\"nofollow noreferrer\">wp_generate_password</a> function</p>\n\n<p><strong>EDIT</strong>\nI have found article <a href=\"https://wisdmlabs.com/blog/how-to-add-a-password-strength-meter-in-wordpress/\" rel=\"nofollow noreferrer\">how to add password strength meter to wordpress</a> which most probably describes, what you want to achieve. Take look at it</p>\n" }, { "answer_id": 358275, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 3, "selected": true, "text": "<p>The minimum requirements are that it passes the <a href=\"https://github.com/dropbox/zxcvbn\" rel=\"nofollow noreferrer\">zxcvbn</a> library's strength check. I can't see a simple summary of their rules. This is registered as script 'zxcvbn-async' that you can enqueue / make a dependency of your own scripts, and then you can run the check yourself on the client-side. See <a href=\"https://github.com/WordPress/WordPress/blob/5.3.2/wp-admin/js/password-strength-meter.js\" rel=\"nofollow noreferrer\">password-strength-meter</a> and <a href=\"https://github.com/WordPress/WordPress/blob/5.3.2/wp-admin/js/user-profile.js#L19\" rel=\"nofollow noreferrer\">user-profile.js</a>'s multiple cases for zxcvbn being not-yet-loaded.</p>\n\n<p>Nowadays WordPress encourages you to use randomly generated passwords</p>\n\n<ul>\n<li>new user registrations always have a randomly generated password</li>\n<li>to change your password in the admin site you click 'generate password' to get a new random one; it does give you the chance to override it but will disable the 'Update profile' button on the page until your password has passed a zxcvbn check.</li>\n</ul>\n\n<p>This is only enforced on the client-side though; there's no server-side enforcement as far as I can see. <a href=\"https://github.com/WordPress/WordPress/blob/5.3.2/wp-admin/includes/user.php#L155\" rel=\"nofollow noreferrer\">user.php</a> does have a <a href=\"https://developer.wordpress.org/reference/hooks/check_passwords/\" rel=\"nofollow noreferrer\">check_passwords</a> action but isn't passed $errors to raise weak password errors itself; you'd have to remember the error and add it in <a href=\"https://developer.wordpress.org/reference/hooks/user_profile_update_errors/\" rel=\"nofollow noreferrer\">user_profile_update_errors</a> later. But there isn't anything like that in a default WordPress install.</p>\n" } ]
2020/02/09
[ "https://wordpress.stackexchange.com/questions/358214", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/171190/" ]
I want to hide page menu from the admin panel for a specific user type. I tried it with the below codes in `functions.php` ``` function hide_menu_items() { global $menu; global $current_user; get_currentuserinfo(); if( $current_user->user_login == 'username' ): remove_menu_page( 'admin.php?page=megamenu' ); remove_menu_page( 'admin.php?page=mycustompage' ); endif; } add_action( 'admin_menu', 'hide_menu_items' ); ``` It's not working but it only hides post\_types
The minimum requirements are that it passes the [zxcvbn](https://github.com/dropbox/zxcvbn) library's strength check. I can't see a simple summary of their rules. This is registered as script 'zxcvbn-async' that you can enqueue / make a dependency of your own scripts, and then you can run the check yourself on the client-side. See [password-strength-meter](https://github.com/WordPress/WordPress/blob/5.3.2/wp-admin/js/password-strength-meter.js) and [user-profile.js](https://github.com/WordPress/WordPress/blob/5.3.2/wp-admin/js/user-profile.js#L19)'s multiple cases for zxcvbn being not-yet-loaded. Nowadays WordPress encourages you to use randomly generated passwords * new user registrations always have a randomly generated password * to change your password in the admin site you click 'generate password' to get a new random one; it does give you the chance to override it but will disable the 'Update profile' button on the page until your password has passed a zxcvbn check. This is only enforced on the client-side though; there's no server-side enforcement as far as I can see. [user.php](https://github.com/WordPress/WordPress/blob/5.3.2/wp-admin/includes/user.php#L155) does have a [check\_passwords](https://developer.wordpress.org/reference/hooks/check_passwords/) action but isn't passed $errors to raise weak password errors itself; you'd have to remember the error and add it in [user\_profile\_update\_errors](https://developer.wordpress.org/reference/hooks/user_profile_update_errors/) later. But there isn't anything like that in a default WordPress install.
358,285
<p>I have a Page like:</p> <pre><code>&lt;?php /* Template Name: Agenda */ get_header(); ?&gt; &lt;div class="wrap"&gt; &lt;div id="primary" class="content-area"&gt; &lt;main id="main" class="site-main" role="main"&gt; My Hompagetext &lt;/main&gt;&lt;!-- #main --&gt; &lt;/div&gt;&lt;!-- #primary --&gt; &lt;?php get_sidebar('test'); ?&gt; &lt;/div&gt;&lt;!-- .wrap --&gt; &lt;?php get_footer();?&gt; </code></pre> <p>I have a sidebar called: sidebar-test.php</p> <pre><code>&lt;aside id="secondary" class="widget-area" role="complementary" aria-label="&lt;?php esc_attr_e( 'Test Sidebar', 'rczo2' ); ?&gt;"&gt; this text is displayed on the bottom but I want it in the sidebar on the right side &lt;/aside&gt;&lt;!-- #secondary --&gt; </code></pre> <p>I tryed reading across the WP-documentation and found how to register a widget, but not how to include a simple script like this.</p>
[ { "answer_id": 358193, "author": "Pavel Janicek", "author_id": 10575, "author_profile": "https://wordpress.stackexchange.com/users/10575", "pm_score": 1, "selected": false, "text": "<p>Surprisingly, for plugin development, correct answer is <strong>none</strong></p>\n\n<p>From <a href=\"https://developer.wordpress.org/reference/functions/wp_set_password/\" rel=\"nofollow noreferrer\">set password documentation</a>:</p>\n\n<pre><code>wp_set_password( string $password, int $user_id )\n</code></pre>\n\n<blockquote>\n <p>Updates the user’s password with a new encrypted one.</p>\n</blockquote>\n\n<p>If you think about security, try going with <a href=\"https://developer.wordpress.org/reference/functions/wp_generate_password/\" rel=\"nofollow noreferrer\">wp_generate_password</a> function</p>\n\n<p><strong>EDIT</strong>\nI have found article <a href=\"https://wisdmlabs.com/blog/how-to-add-a-password-strength-meter-in-wordpress/\" rel=\"nofollow noreferrer\">how to add password strength meter to wordpress</a> which most probably describes, what you want to achieve. Take look at it</p>\n" }, { "answer_id": 358275, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 3, "selected": true, "text": "<p>The minimum requirements are that it passes the <a href=\"https://github.com/dropbox/zxcvbn\" rel=\"nofollow noreferrer\">zxcvbn</a> library's strength check. I can't see a simple summary of their rules. This is registered as script 'zxcvbn-async' that you can enqueue / make a dependency of your own scripts, and then you can run the check yourself on the client-side. See <a href=\"https://github.com/WordPress/WordPress/blob/5.3.2/wp-admin/js/password-strength-meter.js\" rel=\"nofollow noreferrer\">password-strength-meter</a> and <a href=\"https://github.com/WordPress/WordPress/blob/5.3.2/wp-admin/js/user-profile.js#L19\" rel=\"nofollow noreferrer\">user-profile.js</a>'s multiple cases for zxcvbn being not-yet-loaded.</p>\n\n<p>Nowadays WordPress encourages you to use randomly generated passwords</p>\n\n<ul>\n<li>new user registrations always have a randomly generated password</li>\n<li>to change your password in the admin site you click 'generate password' to get a new random one; it does give you the chance to override it but will disable the 'Update profile' button on the page until your password has passed a zxcvbn check.</li>\n</ul>\n\n<p>This is only enforced on the client-side though; there's no server-side enforcement as far as I can see. <a href=\"https://github.com/WordPress/WordPress/blob/5.3.2/wp-admin/includes/user.php#L155\" rel=\"nofollow noreferrer\">user.php</a> does have a <a href=\"https://developer.wordpress.org/reference/hooks/check_passwords/\" rel=\"nofollow noreferrer\">check_passwords</a> action but isn't passed $errors to raise weak password errors itself; you'd have to remember the error and add it in <a href=\"https://developer.wordpress.org/reference/hooks/user_profile_update_errors/\" rel=\"nofollow noreferrer\">user_profile_update_errors</a> later. But there isn't anything like that in a default WordPress install.</p>\n" } ]
2020/02/10
[ "https://wordpress.stackexchange.com/questions/358285", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/182482/" ]
I have a Page like: ``` <?php /* Template Name: Agenda */ get_header(); ?> <div class="wrap"> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> My Hompagetext </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar('test'); ?> </div><!-- .wrap --> <?php get_footer();?> ``` I have a sidebar called: sidebar-test.php ``` <aside id="secondary" class="widget-area" role="complementary" aria-label="<?php esc_attr_e( 'Test Sidebar', 'rczo2' ); ?>"> this text is displayed on the bottom but I want it in the sidebar on the right side </aside><!-- #secondary --> ``` I tryed reading across the WP-documentation and found how to register a widget, but not how to include a simple script like this.
The minimum requirements are that it passes the [zxcvbn](https://github.com/dropbox/zxcvbn) library's strength check. I can't see a simple summary of their rules. This is registered as script 'zxcvbn-async' that you can enqueue / make a dependency of your own scripts, and then you can run the check yourself on the client-side. See [password-strength-meter](https://github.com/WordPress/WordPress/blob/5.3.2/wp-admin/js/password-strength-meter.js) and [user-profile.js](https://github.com/WordPress/WordPress/blob/5.3.2/wp-admin/js/user-profile.js#L19)'s multiple cases for zxcvbn being not-yet-loaded. Nowadays WordPress encourages you to use randomly generated passwords * new user registrations always have a randomly generated password * to change your password in the admin site you click 'generate password' to get a new random one; it does give you the chance to override it but will disable the 'Update profile' button on the page until your password has passed a zxcvbn check. This is only enforced on the client-side though; there's no server-side enforcement as far as I can see. [user.php](https://github.com/WordPress/WordPress/blob/5.3.2/wp-admin/includes/user.php#L155) does have a [check\_passwords](https://developer.wordpress.org/reference/hooks/check_passwords/) action but isn't passed $errors to raise weak password errors itself; you'd have to remember the error and add it in [user\_profile\_update\_errors](https://developer.wordpress.org/reference/hooks/user_profile_update_errors/) later. But there isn't anything like that in a default WordPress install.
358,302
<p>I'm not sure if I'm asking the right question, so here is the context.</p> <p>I'm making a POST to an API (The api is to a Google Sheets Script - so there are some unusual limitations). When I use postman the data is returned in a json file. In order to get it to work in postman I have to send the parameters via the body and I have to select the raw option. Selecting any other option(i.e. x-www-form-urlencoded or form-data) results in an html error page. </p> <p>I've followed the steps for wp_remote_post($api_url , $body ); in the WordPress documentation - but I'm getting the html error instead of the expected data.</p> <p>How do I send the body as "raw" just like it's being sent in Postman?</p> <p>UPDATE - To add code.</p> <pre><code>$api_url = 'https://script.google.com/macros/s/UNIQUE_KEYw/exec'; // $body = array( // "method"=&gt;"GET", // "sheet"=&gt;"date", // "key"=&gt;"PASSWORD"); $body = ('{\n"method": "GET",\n"sheet": "date",\n"key": "PASSWORD"\n}'); $request = wp_remote_post($api_url , array( 'method' =&gt; 'POST', 'headers' =&gt; ["Content-Type" =&gt; "raw"], 'body' =&gt; $body, 'data_format' =&gt; 'body' ) ); </code></pre> <p>The HTTP_Request2 snippet from postman that I'm trying to recreate.</p> <pre><code>&lt;?php require_once 'HTTP/Request2.php'; $request = new HTTP_Request2(); $request-&gt;setUrl('https://script.google.com/macros/s/UNIQUE_KEY/exec'); $request-&gt;setMethod(HTTP_Request2::METHOD_POST); $request-&gt;setConfig(array( 'follow_redirects' =&gt; TRUE )); $request-&gt;setHeader(array( 'Content-Type' =&gt; 'text/plain' )); $request-&gt;setBody('{\n"method": "GET",\n"sheet": "date",\n"key": "PASSWORD"\n}'); try { $response = $request-&gt;send(); if ($response-&gt;getStatus() == 200) { echo $response-&gt;getBody(); } else { echo 'Unexpected HTTP status: ' . $response-&gt;getStatus() . ' ' . $response-&gt;getReasonPhrase(); } } catch(HTTP_Request2_Exception $e) { echo 'Error: ' . $e-&gt;getMessage(); } </code></pre>
[ { "answer_id": 358304, "author": "Tim Elsass", "author_id": 80375, "author_profile": "https://wordpress.stackexchange.com/users/80375", "pm_score": 0, "selected": false, "text": "<p>You should be able to set <code>headers</code> to use <code>content-type: application/json</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$api_url = 'https://script.google.com/macros/s/UNIQUE_KEYw/exec';\n$body = wp_json_encode( array(\n &quot;method&quot; =&gt; &quot;GET&quot;,\n &quot;sheet&quot; =&gt; &quot;date&quot;,\n &quot;key&quot; =&gt; &quot;PASSWORD&quot;\n) );\n\nwp_remote_post( $api_url, [\n 'headers' =&gt; [ 'Content-Type' =&gt; 'application/json' ],\n 'body' =&gt; $body,\n 'data_format' =&gt; 'body'\n] );\n</code></pre>\n" }, { "answer_id": 392850, "author": "Mark Dave Alonzo", "author_id": 209782, "author_profile": "https://wordpress.stackexchange.com/users/209782", "pm_score": 2, "selected": false, "text": "<p>I got this one working, you have to pass the json_encoded array on the body parameter of the request.</p>\n<pre><code> $customer_details = [\n 'first_name' =&gt; $first_name,\n 'last_name' =&gt; $last_name,\n 'email' =&gt; $email,\n ];\n\n $customer_details['body'] = json_encode($customer_details);\n\n $customer = $api-&gt;createUpdateCustomer($customer_details);\n\npublic function createUpdateCustomer($customer_details) {\n $response = $this-&gt;apiCall( &quot;2.0/customers&quot;, 'POST', $customer_details);\n $result = json_decode($response);\n return $result;\n }\n\npublic function apiCall($baseUrl = null, $method = 'GET', $args = array()) {\n if ( !is_null( $baseUrl ) ) {\n $url = $this-&gt;baseUrl . $baseUrl;\n }\n else {\n $url = $this-&gt;baseUrl;\n }\n\n // Populate the args for use in the wp_remote_request call\n $wp_args = array_merge($args, $this-&gt;args);\n $wp_args['method'] = $method;\n $wp_args['timeout'] = 30; \n\n // Make the call and store the response in $res\n $res = wp_remote_request( $url, $wp_args ); \n\n // Check for success\n if ( ! is_wp_error( $res ) &amp;&amp; ( 200 == $res['response']['code'] || 201 == $res['response']['code'] ) ) {\n return $res['body'];\n } else {\n throw new Exception( &quot;API call didn't go well :(. Either VendHQ Connect Settings are incorrect or VendHQ server is not responding as expected.&quot; );\n }\n }\n</code></pre>\n" } ]
2020/02/10
[ "https://wordpress.stackexchange.com/questions/358302", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/182225/" ]
I'm not sure if I'm asking the right question, so here is the context. I'm making a POST to an API (The api is to a Google Sheets Script - so there are some unusual limitations). When I use postman the data is returned in a json file. In order to get it to work in postman I have to send the parameters via the body and I have to select the raw option. Selecting any other option(i.e. x-www-form-urlencoded or form-data) results in an html error page. I've followed the steps for wp\_remote\_post($api\_url , $body ); in the WordPress documentation - but I'm getting the html error instead of the expected data. How do I send the body as "raw" just like it's being sent in Postman? UPDATE - To add code. ``` $api_url = 'https://script.google.com/macros/s/UNIQUE_KEYw/exec'; // $body = array( // "method"=>"GET", // "sheet"=>"date", // "key"=>"PASSWORD"); $body = ('{\n"method": "GET",\n"sheet": "date",\n"key": "PASSWORD"\n}'); $request = wp_remote_post($api_url , array( 'method' => 'POST', 'headers' => ["Content-Type" => "raw"], 'body' => $body, 'data_format' => 'body' ) ); ``` The HTTP\_Request2 snippet from postman that I'm trying to recreate. ``` <?php require_once 'HTTP/Request2.php'; $request = new HTTP_Request2(); $request->setUrl('https://script.google.com/macros/s/UNIQUE_KEY/exec'); $request->setMethod(HTTP_Request2::METHOD_POST); $request->setConfig(array( 'follow_redirects' => TRUE )); $request->setHeader(array( 'Content-Type' => 'text/plain' )); $request->setBody('{\n"method": "GET",\n"sheet": "date",\n"key": "PASSWORD"\n}'); try { $response = $request->send(); if ($response->getStatus() == 200) { echo $response->getBody(); } else { echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' . $response->getReasonPhrase(); } } catch(HTTP_Request2_Exception $e) { echo 'Error: ' . $e->getMessage(); } ```
I got this one working, you have to pass the json\_encoded array on the body parameter of the request. ``` $customer_details = [ 'first_name' => $first_name, 'last_name' => $last_name, 'email' => $email, ]; $customer_details['body'] = json_encode($customer_details); $customer = $api->createUpdateCustomer($customer_details); public function createUpdateCustomer($customer_details) { $response = $this->apiCall( "2.0/customers", 'POST', $customer_details); $result = json_decode($response); return $result; } public function apiCall($baseUrl = null, $method = 'GET', $args = array()) { if ( !is_null( $baseUrl ) ) { $url = $this->baseUrl . $baseUrl; } else { $url = $this->baseUrl; } // Populate the args for use in the wp_remote_request call $wp_args = array_merge($args, $this->args); $wp_args['method'] = $method; $wp_args['timeout'] = 30; // Make the call and store the response in $res $res = wp_remote_request( $url, $wp_args ); // Check for success if ( ! is_wp_error( $res ) && ( 200 == $res['response']['code'] || 201 == $res['response']['code'] ) ) { return $res['body']; } else { throw new Exception( "API call didn't go well :(. Either VendHQ Connect Settings are incorrect or VendHQ server is not responding as expected." ); } } ```
358,347
<p>I have followed the documentation of WordPress on translating Gutenberg block, I have used WP CLI to create the .pot, .po and .json file and uploaded to my langauges folder inside the folder of that plugin, but still it is not working. Can someone tell me whats wrong with my code?</p> <p>PHP:</p> <pre><code>function custom_blocks_load_plugin_textdomain() { load_plugin_textdomain( 'custom-blocks', FALSE, ''); } add_action( 'plugins_loaded', 'custom_blocks_load_plugin_textdomain' ); //register block template function block_registration_template($block_path, $block_handle, $script_handle, $render_callback = false){ wp_register_script( $script_handle, plugins_url( $block_path , __FILE__ ), [ 'wp-i18n', 'wp-element', 'wp-blocks', 'wp-components', 'wp-editor' ], filemtime( plugin_dir_path( $block_path , __FILE__ ) ) ); $parameters = array( 'editor_script' =&gt; $script_handle, ); if($render_callback){ $parameters['render_callback'] = $render_callback; } register_block_type( $block_handle, $parameters ); } function block_registration(){ block_registration_template('/ref_block.js', 'custom-blocks/ref', 'CUSTOM-block-ref'); block_registration_template('/ref_holder_block.js', 'custom-blocks/ref-holder', 'CUSTOM-block-ref-holder'); } add_action('init', 'block_registration'); function custom_blocks_set_script_translations() { wp_set_script_translations( 'CUSTOM-block-ref-holder', 'custom-blocks'); } add_action( 'init', 'custom_blocks_set_script_translations' ); </code></pre> <p>JS</p> <pre><code>(() =&gt; { const __ = wp.i18n.__; // The __() for internationalization. const el = wp.element.createElement; // The wp.element.createElement() function to create elements. const registerBlockType = wp.blocks.registerBlockType; // The registerBlockType() to register blocks. const ServerSideRender = wp.components.ServerSideRender; const TextControl = wp.components.TextControl; const TextareaControl = wp.components.TextareaControl; const InspectorControls = wp.editor.InspectorControls; const { RichText } = wp.blockEditor; const { InnerBlocks } = wp.blockEditor; //Custom variable const allowedBlocks = [ 'custom-blocks/ref' ] ; const blockTemplate = [ [ 'custom-blocks/ref', {} ] ]; registerBlockType( 'custom-blocks/ref-holder', { // Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block. title: __( 'Reference Holder', 'custom-blocks' ), // Block title. category: 'custom_block', keywords: [ __('ref'), 'custom-blocks'], attributes: { }, supports: { customClassName: false, className: false, }, edit(props) { return el( 'div', { className: 'ref-block-holder'}, el('h2', {}, __('Reference', 'custom-blocks') ), el ( InnerBlocks, { allowedBlocks: allowedBlocks, template: blockTemplate } ) ); }, save(props) { return el( 'div', { className: 'ref-block-holder'}, el('h2', {}, __('Reference', 'custom-blocks') ), el ( InnerBlocks.Content, { allowedBlocks: allowedBlocks, template: blockTemplate } ) ); }, }); })(); </code></pre> <p>JSON:</p> <pre><code>{ "translation-revision-date":"2020-02-10 15:33+0800", "generator":"WP-CLI/2.4.0", "source":"ref_holder_block.js", "domain":"custom-blocks", "locale_data":{ "messages":{ "":{ "domain":"custom-blocks", "lang":"zh_HK", "plural-forms":"nplurals=1; plural=0;" }, "Reference":[ "\u53c3\u8003\u8cc7\u6599" ], "Reference Holder":[ "" ] } } } </code></pre> <p>Any help would be appreciated. Thanks!</p>
[ { "answer_id": 358304, "author": "Tim Elsass", "author_id": 80375, "author_profile": "https://wordpress.stackexchange.com/users/80375", "pm_score": 0, "selected": false, "text": "<p>You should be able to set <code>headers</code> to use <code>content-type: application/json</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$api_url = 'https://script.google.com/macros/s/UNIQUE_KEYw/exec';\n$body = wp_json_encode( array(\n &quot;method&quot; =&gt; &quot;GET&quot;,\n &quot;sheet&quot; =&gt; &quot;date&quot;,\n &quot;key&quot; =&gt; &quot;PASSWORD&quot;\n) );\n\nwp_remote_post( $api_url, [\n 'headers' =&gt; [ 'Content-Type' =&gt; 'application/json' ],\n 'body' =&gt; $body,\n 'data_format' =&gt; 'body'\n] );\n</code></pre>\n" }, { "answer_id": 392850, "author": "Mark Dave Alonzo", "author_id": 209782, "author_profile": "https://wordpress.stackexchange.com/users/209782", "pm_score": 2, "selected": false, "text": "<p>I got this one working, you have to pass the json_encoded array on the body parameter of the request.</p>\n<pre><code> $customer_details = [\n 'first_name' =&gt; $first_name,\n 'last_name' =&gt; $last_name,\n 'email' =&gt; $email,\n ];\n\n $customer_details['body'] = json_encode($customer_details);\n\n $customer = $api-&gt;createUpdateCustomer($customer_details);\n\npublic function createUpdateCustomer($customer_details) {\n $response = $this-&gt;apiCall( &quot;2.0/customers&quot;, 'POST', $customer_details);\n $result = json_decode($response);\n return $result;\n }\n\npublic function apiCall($baseUrl = null, $method = 'GET', $args = array()) {\n if ( !is_null( $baseUrl ) ) {\n $url = $this-&gt;baseUrl . $baseUrl;\n }\n else {\n $url = $this-&gt;baseUrl;\n }\n\n // Populate the args for use in the wp_remote_request call\n $wp_args = array_merge($args, $this-&gt;args);\n $wp_args['method'] = $method;\n $wp_args['timeout'] = 30; \n\n // Make the call and store the response in $res\n $res = wp_remote_request( $url, $wp_args ); \n\n // Check for success\n if ( ! is_wp_error( $res ) &amp;&amp; ( 200 == $res['response']['code'] || 201 == $res['response']['code'] ) ) {\n return $res['body'];\n } else {\n throw new Exception( &quot;API call didn't go well :(. Either VendHQ Connect Settings are incorrect or VendHQ server is not responding as expected.&quot; );\n }\n }\n</code></pre>\n" } ]
2020/02/11
[ "https://wordpress.stackexchange.com/questions/358347", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/180921/" ]
I have followed the documentation of WordPress on translating Gutenberg block, I have used WP CLI to create the .pot, .po and .json file and uploaded to my langauges folder inside the folder of that plugin, but still it is not working. Can someone tell me whats wrong with my code? PHP: ``` function custom_blocks_load_plugin_textdomain() { load_plugin_textdomain( 'custom-blocks', FALSE, ''); } add_action( 'plugins_loaded', 'custom_blocks_load_plugin_textdomain' ); //register block template function block_registration_template($block_path, $block_handle, $script_handle, $render_callback = false){ wp_register_script( $script_handle, plugins_url( $block_path , __FILE__ ), [ 'wp-i18n', 'wp-element', 'wp-blocks', 'wp-components', 'wp-editor' ], filemtime( plugin_dir_path( $block_path , __FILE__ ) ) ); $parameters = array( 'editor_script' => $script_handle, ); if($render_callback){ $parameters['render_callback'] = $render_callback; } register_block_type( $block_handle, $parameters ); } function block_registration(){ block_registration_template('/ref_block.js', 'custom-blocks/ref', 'CUSTOM-block-ref'); block_registration_template('/ref_holder_block.js', 'custom-blocks/ref-holder', 'CUSTOM-block-ref-holder'); } add_action('init', 'block_registration'); function custom_blocks_set_script_translations() { wp_set_script_translations( 'CUSTOM-block-ref-holder', 'custom-blocks'); } add_action( 'init', 'custom_blocks_set_script_translations' ); ``` JS ``` (() => { const __ = wp.i18n.__; // The __() for internationalization. const el = wp.element.createElement; // The wp.element.createElement() function to create elements. const registerBlockType = wp.blocks.registerBlockType; // The registerBlockType() to register blocks. const ServerSideRender = wp.components.ServerSideRender; const TextControl = wp.components.TextControl; const TextareaControl = wp.components.TextareaControl; const InspectorControls = wp.editor.InspectorControls; const { RichText } = wp.blockEditor; const { InnerBlocks } = wp.blockEditor; //Custom variable const allowedBlocks = [ 'custom-blocks/ref' ] ; const blockTemplate = [ [ 'custom-blocks/ref', {} ] ]; registerBlockType( 'custom-blocks/ref-holder', { // Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block. title: __( 'Reference Holder', 'custom-blocks' ), // Block title. category: 'custom_block', keywords: [ __('ref'), 'custom-blocks'], attributes: { }, supports: { customClassName: false, className: false, }, edit(props) { return el( 'div', { className: 'ref-block-holder'}, el('h2', {}, __('Reference', 'custom-blocks') ), el ( InnerBlocks, { allowedBlocks: allowedBlocks, template: blockTemplate } ) ); }, save(props) { return el( 'div', { className: 'ref-block-holder'}, el('h2', {}, __('Reference', 'custom-blocks') ), el ( InnerBlocks.Content, { allowedBlocks: allowedBlocks, template: blockTemplate } ) ); }, }); })(); ``` JSON: ``` { "translation-revision-date":"2020-02-10 15:33+0800", "generator":"WP-CLI/2.4.0", "source":"ref_holder_block.js", "domain":"custom-blocks", "locale_data":{ "messages":{ "":{ "domain":"custom-blocks", "lang":"zh_HK", "plural-forms":"nplurals=1; plural=0;" }, "Reference":[ "\u53c3\u8003\u8cc7\u6599" ], "Reference Holder":[ "" ] } } } ``` Any help would be appreciated. Thanks!
I got this one working, you have to pass the json\_encoded array on the body parameter of the request. ``` $customer_details = [ 'first_name' => $first_name, 'last_name' => $last_name, 'email' => $email, ]; $customer_details['body'] = json_encode($customer_details); $customer = $api->createUpdateCustomer($customer_details); public function createUpdateCustomer($customer_details) { $response = $this->apiCall( "2.0/customers", 'POST', $customer_details); $result = json_decode($response); return $result; } public function apiCall($baseUrl = null, $method = 'GET', $args = array()) { if ( !is_null( $baseUrl ) ) { $url = $this->baseUrl . $baseUrl; } else { $url = $this->baseUrl; } // Populate the args for use in the wp_remote_request call $wp_args = array_merge($args, $this->args); $wp_args['method'] = $method; $wp_args['timeout'] = 30; // Make the call and store the response in $res $res = wp_remote_request( $url, $wp_args ); // Check for success if ( ! is_wp_error( $res ) && ( 200 == $res['response']['code'] || 201 == $res['response']['code'] ) ) { return $res['body']; } else { throw new Exception( "API call didn't go well :(. Either VendHQ Connect Settings are incorrect or VendHQ server is not responding as expected." ); } } ```
358,373
<p>The following code comes from one of the Gutenberg blocks official examples. The block is pretty simple and just create an editable field that outputs a <code>p</code> element.</p> <pre><code>registerBlockType( 'gutenberg-examples/example-03-editable-esnext', { title: __( 'Example: Editable (ESNext)', 'gutenberg-examples' ), icon: 'universal-access-alt', category: 'layout', attributes: { content: { type: 'array', source: 'children', selector: 'p', }, }, edit: ( props ) =&gt; { const { attributes: { content }, setAttributes, className } = props; const onChangeContent = ( newContent ) =&gt; { setAttributes( { content: newContent } ); }; return ( &lt;RichText tagName="p" className={ className } onChange={ onChangeContent } value={ content } /&gt; ); }, save: ( props ) =&gt; { return &lt;RichText.Content tagName="p" value={ props.attributes.content } /&gt;; }, } ); </code></pre> <p>If used, this block produces a <code>p</code> element with a class like this:</p> <pre><code>&lt;p class="wp-block-gutenberg-examples-example-03-editable-esnext"&gt;&lt;/p&gt; </code></pre> <p>which I'm assuming is built upon the <code>registerBlockType</code> parameter.</p> <p>My question is: is it possible to print the output of a custom block without any class specification?</p> <p><strong>edit:</strong> <a href="https://developer.wordpress.org/block-editor/developers/filters/block-filters/#blocks-getblockdefaultclassname" rel="nofollow noreferrer">Wordpress docs say</a> there is a filter to change the default class name, which is this:</p> <pre><code>wp.hooks.addFilter( 'blocks.getBlockDefaultClassName', 'my-plugin/set-block-custom-class-name', setBlockCustomClassName ); </code></pre> <p>Now, where exactly does this code go? Can't find it in the docs.</p>
[ { "answer_id": 358396, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": true, "text": "<p>The code from the docs is JavaScript. You have to set up Webpack and build this type of JS. So, you could use something like Create-Guten-Block to set up that build process, and then replace the contents of \"block.js\" with that JS from the docs. (I sure wish they would improve the docs to make things like this clearer.)</p>\n\n<p>Or, you could choose to filter with PHP, which instead of preventing the class from being added in the first place, processes the data saved in the database and could strip out the CSS class. (Then if you ever wanted to include the Core classes, you'd just remove your filter and they would all appear - because they're all still saved in the database.) You would do something like</p>\n\n<pre><code>&lt;?php\nadd_filter('render_block', function($block_content, $block) {\n // Only affect this specific block\n if('gutenberg-examples/example-03-editable-esnext' === $block['blockName']) {\n $block_content = str_replace('class=\"wp-block-gutenberg-examples-example-03-editable-esnext\"', '', $block_content);\n }\n // Always return the content\n return $block_content;\n}, 10, 2);\n?&gt;\n</code></pre>\n\n<p>inside a custom plugin or your custom/child theme's functions.php file.</p>\n\n<p>Or - you could always go back and edit the block itself, in which case again you would need to set up the build process. I'm a little confused that the <code>save()</code> function doesn't actually refer to any <code>className</code>, but it looks like if you changed the <code>edit()</code> function so that it no longer had a <code>className</code>, that would likely remove the class.</p>\n" }, { "answer_id": 358404, "author": "Old Nick", "author_id": 122690, "author_profile": "https://wordpress.stackexchange.com/users/122690", "pm_score": 1, "selected": false, "text": "<p>Since @WebElaine didn't specify the js way, I'll add it myself. The full code to add is this:</p>\n\n<pre><code>function setBlockCustomClassName( className, blockName ) {\n return blockName === 'gutenberg-examples/example-03-editable-esnext' ? //this is the block identifier, taken from the registerBlockType\n 'new class name' : //this is class name we want to associate by default to the block, in my case it's an empty string since I don't want any class \n className;\n}\n\nwp.hooks.addFilter(\n 'blocks.getBlockDefaultClassName',\n 'gutenberg-examples/example-03-editable-esnext', //this is again the block identifier, taken from the registerBlockType\n setBlockCustomClassName\n);\n</code></pre>\n\n<p>Putting it all togheter, the full code is:</p>\n\n<pre><code>registerBlockType( 'gutenberg-examples/example-03-editable-esnext', {\n title: __( 'Example: Editable (ESNext)', 'gutenberg-examples' ),\n icon: 'universal-access-alt',\n category: 'layout',\n attributes: {\n content: {\n type: 'array',\n source: 'children',\n selector: 'p',\n },\n },\n edit: ( props ) =&gt; {\n const { attributes: { content }, setAttributes, className } = props;\n const onChangeContent = ( newContent ) =&gt; {\n setAttributes( { content: newContent } );\n };\n return (\n &lt;RichText\n tagName=\"p\"\n className={ className }\n onChange={ onChangeContent }\n value={ content }\n /&gt;\n );\n },\n save: ( props ) =&gt; {\n return &lt;RichText.Content tagName=\"p\" value={ props.attributes.content } /&gt;;\n },\n});\n//Old code ended here\nfunction setBlockCustomClassName( className, blockName ) {\n return blockName === 'gutenberg-examples/example-03-editable-esnext' ? //this is the block identifier, taken from the registerBlockType\n 'new class name' : //this is class name we want to associate by default to the block, in my case it's an empty string since I don't want any class \n className;\n}\nwp.hooks.addFilter(\n 'blocks.getBlockDefaultClassName',\n 'gutenberg-examples/example-03-editable-esnext', //this is again the block identifier, taken from the registerBlockType\n setBlockCustomClassName\n);\n</code></pre>\n\n<p>In the case of a simple block, all this stuff goes into the main js file (usually <code>index.js</code>) associated with the plugin.</p>\n" } ]
2020/02/11
[ "https://wordpress.stackexchange.com/questions/358373", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122690/" ]
The following code comes from one of the Gutenberg blocks official examples. The block is pretty simple and just create an editable field that outputs a `p` element. ``` registerBlockType( 'gutenberg-examples/example-03-editable-esnext', { title: __( 'Example: Editable (ESNext)', 'gutenberg-examples' ), icon: 'universal-access-alt', category: 'layout', attributes: { content: { type: 'array', source: 'children', selector: 'p', }, }, edit: ( props ) => { const { attributes: { content }, setAttributes, className } = props; const onChangeContent = ( newContent ) => { setAttributes( { content: newContent } ); }; return ( <RichText tagName="p" className={ className } onChange={ onChangeContent } value={ content } /> ); }, save: ( props ) => { return <RichText.Content tagName="p" value={ props.attributes.content } />; }, } ); ``` If used, this block produces a `p` element with a class like this: ``` <p class="wp-block-gutenberg-examples-example-03-editable-esnext"></p> ``` which I'm assuming is built upon the `registerBlockType` parameter. My question is: is it possible to print the output of a custom block without any class specification? **edit:** [Wordpress docs say](https://developer.wordpress.org/block-editor/developers/filters/block-filters/#blocks-getblockdefaultclassname) there is a filter to change the default class name, which is this: ``` wp.hooks.addFilter( 'blocks.getBlockDefaultClassName', 'my-plugin/set-block-custom-class-name', setBlockCustomClassName ); ``` Now, where exactly does this code go? Can't find it in the docs.
The code from the docs is JavaScript. You have to set up Webpack and build this type of JS. So, you could use something like Create-Guten-Block to set up that build process, and then replace the contents of "block.js" with that JS from the docs. (I sure wish they would improve the docs to make things like this clearer.) Or, you could choose to filter with PHP, which instead of preventing the class from being added in the first place, processes the data saved in the database and could strip out the CSS class. (Then if you ever wanted to include the Core classes, you'd just remove your filter and they would all appear - because they're all still saved in the database.) You would do something like ``` <?php add_filter('render_block', function($block_content, $block) { // Only affect this specific block if('gutenberg-examples/example-03-editable-esnext' === $block['blockName']) { $block_content = str_replace('class="wp-block-gutenberg-examples-example-03-editable-esnext"', '', $block_content); } // Always return the content return $block_content; }, 10, 2); ?> ``` inside a custom plugin or your custom/child theme's functions.php file. Or - you could always go back and edit the block itself, in which case again you would need to set up the build process. I'm a little confused that the `save()` function doesn't actually refer to any `className`, but it looks like if you changed the `edit()` function so that it no longer had a `className`, that would likely remove the class.
358,414
<p>I want to limit the access to a wordpress app only to registered users.</p> <p>I've putted this inside the function file, but I'm able to see the home also if I'm not logged in. How I fix this?</p> <pre><code>if( is_home() || is_page() || is_single() &amp;&amp; !is_user_logged_in() ){ wp_safe_redirect( wp_login_url() ); } </code></pre>
[ { "answer_id": 358396, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": true, "text": "<p>The code from the docs is JavaScript. You have to set up Webpack and build this type of JS. So, you could use something like Create-Guten-Block to set up that build process, and then replace the contents of \"block.js\" with that JS from the docs. (I sure wish they would improve the docs to make things like this clearer.)</p>\n\n<p>Or, you could choose to filter with PHP, which instead of preventing the class from being added in the first place, processes the data saved in the database and could strip out the CSS class. (Then if you ever wanted to include the Core classes, you'd just remove your filter and they would all appear - because they're all still saved in the database.) You would do something like</p>\n\n<pre><code>&lt;?php\nadd_filter('render_block', function($block_content, $block) {\n // Only affect this specific block\n if('gutenberg-examples/example-03-editable-esnext' === $block['blockName']) {\n $block_content = str_replace('class=\"wp-block-gutenberg-examples-example-03-editable-esnext\"', '', $block_content);\n }\n // Always return the content\n return $block_content;\n}, 10, 2);\n?&gt;\n</code></pre>\n\n<p>inside a custom plugin or your custom/child theme's functions.php file.</p>\n\n<p>Or - you could always go back and edit the block itself, in which case again you would need to set up the build process. I'm a little confused that the <code>save()</code> function doesn't actually refer to any <code>className</code>, but it looks like if you changed the <code>edit()</code> function so that it no longer had a <code>className</code>, that would likely remove the class.</p>\n" }, { "answer_id": 358404, "author": "Old Nick", "author_id": 122690, "author_profile": "https://wordpress.stackexchange.com/users/122690", "pm_score": 1, "selected": false, "text": "<p>Since @WebElaine didn't specify the js way, I'll add it myself. The full code to add is this:</p>\n\n<pre><code>function setBlockCustomClassName( className, blockName ) {\n return blockName === 'gutenberg-examples/example-03-editable-esnext' ? //this is the block identifier, taken from the registerBlockType\n 'new class name' : //this is class name we want to associate by default to the block, in my case it's an empty string since I don't want any class \n className;\n}\n\nwp.hooks.addFilter(\n 'blocks.getBlockDefaultClassName',\n 'gutenberg-examples/example-03-editable-esnext', //this is again the block identifier, taken from the registerBlockType\n setBlockCustomClassName\n);\n</code></pre>\n\n<p>Putting it all togheter, the full code is:</p>\n\n<pre><code>registerBlockType( 'gutenberg-examples/example-03-editable-esnext', {\n title: __( 'Example: Editable (ESNext)', 'gutenberg-examples' ),\n icon: 'universal-access-alt',\n category: 'layout',\n attributes: {\n content: {\n type: 'array',\n source: 'children',\n selector: 'p',\n },\n },\n edit: ( props ) =&gt; {\n const { attributes: { content }, setAttributes, className } = props;\n const onChangeContent = ( newContent ) =&gt; {\n setAttributes( { content: newContent } );\n };\n return (\n &lt;RichText\n tagName=\"p\"\n className={ className }\n onChange={ onChangeContent }\n value={ content }\n /&gt;\n );\n },\n save: ( props ) =&gt; {\n return &lt;RichText.Content tagName=\"p\" value={ props.attributes.content } /&gt;;\n },\n});\n//Old code ended here\nfunction setBlockCustomClassName( className, blockName ) {\n return blockName === 'gutenberg-examples/example-03-editable-esnext' ? //this is the block identifier, taken from the registerBlockType\n 'new class name' : //this is class name we want to associate by default to the block, in my case it's an empty string since I don't want any class \n className;\n}\nwp.hooks.addFilter(\n 'blocks.getBlockDefaultClassName',\n 'gutenberg-examples/example-03-editable-esnext', //this is again the block identifier, taken from the registerBlockType\n setBlockCustomClassName\n);\n</code></pre>\n\n<p>In the case of a simple block, all this stuff goes into the main js file (usually <code>index.js</code>) associated with the plugin.</p>\n" } ]
2020/02/11
[ "https://wordpress.stackexchange.com/questions/358414", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/177581/" ]
I want to limit the access to a wordpress app only to registered users. I've putted this inside the function file, but I'm able to see the home also if I'm not logged in. How I fix this? ``` if( is_home() || is_page() || is_single() && !is_user_logged_in() ){ wp_safe_redirect( wp_login_url() ); } ```
The code from the docs is JavaScript. You have to set up Webpack and build this type of JS. So, you could use something like Create-Guten-Block to set up that build process, and then replace the contents of "block.js" with that JS from the docs. (I sure wish they would improve the docs to make things like this clearer.) Or, you could choose to filter with PHP, which instead of preventing the class from being added in the first place, processes the data saved in the database and could strip out the CSS class. (Then if you ever wanted to include the Core classes, you'd just remove your filter and they would all appear - because they're all still saved in the database.) You would do something like ``` <?php add_filter('render_block', function($block_content, $block) { // Only affect this specific block if('gutenberg-examples/example-03-editable-esnext' === $block['blockName']) { $block_content = str_replace('class="wp-block-gutenberg-examples-example-03-editable-esnext"', '', $block_content); } // Always return the content return $block_content; }, 10, 2); ?> ``` inside a custom plugin or your custom/child theme's functions.php file. Or - you could always go back and edit the block itself, in which case again you would need to set up the build process. I'm a little confused that the `save()` function doesn't actually refer to any `className`, but it looks like if you changed the `edit()` function so that it no longer had a `className`, that would likely remove the class.
358,421
<p>I'm trying to disable a form button (contact form 7) after submitting and then save the disabled state to localstorage. This disables the button after submitting:</p> <pre><code>jQuery(document).ready(function($) { $("#buttonID").click(function () { setTimeout(function () { disableButton(); }, 100); }); function disableButton() { $("#buttonID").prop('disabled', true); } }); </code></pre> <p>How can I save the disabled state to localstorage so it stays disable?</p>
[ { "answer_id": 358396, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": true, "text": "<p>The code from the docs is JavaScript. You have to set up Webpack and build this type of JS. So, you could use something like Create-Guten-Block to set up that build process, and then replace the contents of \"block.js\" with that JS from the docs. (I sure wish they would improve the docs to make things like this clearer.)</p>\n\n<p>Or, you could choose to filter with PHP, which instead of preventing the class from being added in the first place, processes the data saved in the database and could strip out the CSS class. (Then if you ever wanted to include the Core classes, you'd just remove your filter and they would all appear - because they're all still saved in the database.) You would do something like</p>\n\n<pre><code>&lt;?php\nadd_filter('render_block', function($block_content, $block) {\n // Only affect this specific block\n if('gutenberg-examples/example-03-editable-esnext' === $block['blockName']) {\n $block_content = str_replace('class=\"wp-block-gutenberg-examples-example-03-editable-esnext\"', '', $block_content);\n }\n // Always return the content\n return $block_content;\n}, 10, 2);\n?&gt;\n</code></pre>\n\n<p>inside a custom plugin or your custom/child theme's functions.php file.</p>\n\n<p>Or - you could always go back and edit the block itself, in which case again you would need to set up the build process. I'm a little confused that the <code>save()</code> function doesn't actually refer to any <code>className</code>, but it looks like if you changed the <code>edit()</code> function so that it no longer had a <code>className</code>, that would likely remove the class.</p>\n" }, { "answer_id": 358404, "author": "Old Nick", "author_id": 122690, "author_profile": "https://wordpress.stackexchange.com/users/122690", "pm_score": 1, "selected": false, "text": "<p>Since @WebElaine didn't specify the js way, I'll add it myself. The full code to add is this:</p>\n\n<pre><code>function setBlockCustomClassName( className, blockName ) {\n return blockName === 'gutenberg-examples/example-03-editable-esnext' ? //this is the block identifier, taken from the registerBlockType\n 'new class name' : //this is class name we want to associate by default to the block, in my case it's an empty string since I don't want any class \n className;\n}\n\nwp.hooks.addFilter(\n 'blocks.getBlockDefaultClassName',\n 'gutenberg-examples/example-03-editable-esnext', //this is again the block identifier, taken from the registerBlockType\n setBlockCustomClassName\n);\n</code></pre>\n\n<p>Putting it all togheter, the full code is:</p>\n\n<pre><code>registerBlockType( 'gutenberg-examples/example-03-editable-esnext', {\n title: __( 'Example: Editable (ESNext)', 'gutenberg-examples' ),\n icon: 'universal-access-alt',\n category: 'layout',\n attributes: {\n content: {\n type: 'array',\n source: 'children',\n selector: 'p',\n },\n },\n edit: ( props ) =&gt; {\n const { attributes: { content }, setAttributes, className } = props;\n const onChangeContent = ( newContent ) =&gt; {\n setAttributes( { content: newContent } );\n };\n return (\n &lt;RichText\n tagName=\"p\"\n className={ className }\n onChange={ onChangeContent }\n value={ content }\n /&gt;\n );\n },\n save: ( props ) =&gt; {\n return &lt;RichText.Content tagName=\"p\" value={ props.attributes.content } /&gt;;\n },\n});\n//Old code ended here\nfunction setBlockCustomClassName( className, blockName ) {\n return blockName === 'gutenberg-examples/example-03-editable-esnext' ? //this is the block identifier, taken from the registerBlockType\n 'new class name' : //this is class name we want to associate by default to the block, in my case it's an empty string since I don't want any class \n className;\n}\nwp.hooks.addFilter(\n 'blocks.getBlockDefaultClassName',\n 'gutenberg-examples/example-03-editable-esnext', //this is again the block identifier, taken from the registerBlockType\n setBlockCustomClassName\n);\n</code></pre>\n\n<p>In the case of a simple block, all this stuff goes into the main js file (usually <code>index.js</code>) associated with the plugin.</p>\n" } ]
2020/02/11
[ "https://wordpress.stackexchange.com/questions/358421", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135201/" ]
I'm trying to disable a form button (contact form 7) after submitting and then save the disabled state to localstorage. This disables the button after submitting: ``` jQuery(document).ready(function($) { $("#buttonID").click(function () { setTimeout(function () { disableButton(); }, 100); }); function disableButton() { $("#buttonID").prop('disabled', true); } }); ``` How can I save the disabled state to localstorage so it stays disable?
The code from the docs is JavaScript. You have to set up Webpack and build this type of JS. So, you could use something like Create-Guten-Block to set up that build process, and then replace the contents of "block.js" with that JS from the docs. (I sure wish they would improve the docs to make things like this clearer.) Or, you could choose to filter with PHP, which instead of preventing the class from being added in the first place, processes the data saved in the database and could strip out the CSS class. (Then if you ever wanted to include the Core classes, you'd just remove your filter and they would all appear - because they're all still saved in the database.) You would do something like ``` <?php add_filter('render_block', function($block_content, $block) { // Only affect this specific block if('gutenberg-examples/example-03-editable-esnext' === $block['blockName']) { $block_content = str_replace('class="wp-block-gutenberg-examples-example-03-editable-esnext"', '', $block_content); } // Always return the content return $block_content; }, 10, 2); ?> ``` inside a custom plugin or your custom/child theme's functions.php file. Or - you could always go back and edit the block itself, in which case again you would need to set up the build process. I'm a little confused that the `save()` function doesn't actually refer to any `className`, but it looks like if you changed the `edit()` function so that it no longer had a `className`, that would likely remove the class.
358,428
<p>I'm creating a block and using rich text to save some text this is my edit function.</p> <pre><code> edit: (props) =&gt; { const { attributes: { content, backgroundImage }, setAttributes } = props; const onImageSelect = (imageObject) =&gt; { setAttributes({ backgroundImage: imageObject.sizes.full.url }); } const onChangeContent = (newContent) =&gt; { setAttributes({ content: newContent }); }; console.log(content); return ( &lt;div className={props.className}&gt; &lt;MediaUpload onSelect={onImageSelect} type="image" value={backgroundImage} render={({ open }) =&gt; ( &lt;button onClick={open}&gt; Upload Image! &lt;/button&gt; )} /&gt; &lt;img src={backgroundImage} alt="eherh" /&gt; &lt;div className={'caption'}&gt; &lt;RichText tagName={"p"} className={'imgCtaContent'} onChange={onChangeContent} value={content} placeholder="Enter text..." /&gt; &lt;/div&gt; &lt;/div&gt; ); }, </code></pre> <p>and this is my save function: - </p> <pre><code> save: (props) =&gt; { return ( &lt;div className={props.className}&gt; &lt;RichText.Content tagName={"p"} value={props.attributes.content} /&gt; &lt;/div&gt; ); }, </code></pre> <p>I can see when I type into the block when I'm editing it that the console.log(content) displays the content but when I save the page the text isn't saved.</p> <p>Where am I going wrong?</p>
[ { "answer_id": 358396, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": true, "text": "<p>The code from the docs is JavaScript. You have to set up Webpack and build this type of JS. So, you could use something like Create-Guten-Block to set up that build process, and then replace the contents of \"block.js\" with that JS from the docs. (I sure wish they would improve the docs to make things like this clearer.)</p>\n\n<p>Or, you could choose to filter with PHP, which instead of preventing the class from being added in the first place, processes the data saved in the database and could strip out the CSS class. (Then if you ever wanted to include the Core classes, you'd just remove your filter and they would all appear - because they're all still saved in the database.) You would do something like</p>\n\n<pre><code>&lt;?php\nadd_filter('render_block', function($block_content, $block) {\n // Only affect this specific block\n if('gutenberg-examples/example-03-editable-esnext' === $block['blockName']) {\n $block_content = str_replace('class=\"wp-block-gutenberg-examples-example-03-editable-esnext\"', '', $block_content);\n }\n // Always return the content\n return $block_content;\n}, 10, 2);\n?&gt;\n</code></pre>\n\n<p>inside a custom plugin or your custom/child theme's functions.php file.</p>\n\n<p>Or - you could always go back and edit the block itself, in which case again you would need to set up the build process. I'm a little confused that the <code>save()</code> function doesn't actually refer to any <code>className</code>, but it looks like if you changed the <code>edit()</code> function so that it no longer had a <code>className</code>, that would likely remove the class.</p>\n" }, { "answer_id": 358404, "author": "Old Nick", "author_id": 122690, "author_profile": "https://wordpress.stackexchange.com/users/122690", "pm_score": 1, "selected": false, "text": "<p>Since @WebElaine didn't specify the js way, I'll add it myself. The full code to add is this:</p>\n\n<pre><code>function setBlockCustomClassName( className, blockName ) {\n return blockName === 'gutenberg-examples/example-03-editable-esnext' ? //this is the block identifier, taken from the registerBlockType\n 'new class name' : //this is class name we want to associate by default to the block, in my case it's an empty string since I don't want any class \n className;\n}\n\nwp.hooks.addFilter(\n 'blocks.getBlockDefaultClassName',\n 'gutenberg-examples/example-03-editable-esnext', //this is again the block identifier, taken from the registerBlockType\n setBlockCustomClassName\n);\n</code></pre>\n\n<p>Putting it all togheter, the full code is:</p>\n\n<pre><code>registerBlockType( 'gutenberg-examples/example-03-editable-esnext', {\n title: __( 'Example: Editable (ESNext)', 'gutenberg-examples' ),\n icon: 'universal-access-alt',\n category: 'layout',\n attributes: {\n content: {\n type: 'array',\n source: 'children',\n selector: 'p',\n },\n },\n edit: ( props ) =&gt; {\n const { attributes: { content }, setAttributes, className } = props;\n const onChangeContent = ( newContent ) =&gt; {\n setAttributes( { content: newContent } );\n };\n return (\n &lt;RichText\n tagName=\"p\"\n className={ className }\n onChange={ onChangeContent }\n value={ content }\n /&gt;\n );\n },\n save: ( props ) =&gt; {\n return &lt;RichText.Content tagName=\"p\" value={ props.attributes.content } /&gt;;\n },\n});\n//Old code ended here\nfunction setBlockCustomClassName( className, blockName ) {\n return blockName === 'gutenberg-examples/example-03-editable-esnext' ? //this is the block identifier, taken from the registerBlockType\n 'new class name' : //this is class name we want to associate by default to the block, in my case it's an empty string since I don't want any class \n className;\n}\nwp.hooks.addFilter(\n 'blocks.getBlockDefaultClassName',\n 'gutenberg-examples/example-03-editable-esnext', //this is again the block identifier, taken from the registerBlockType\n setBlockCustomClassName\n);\n</code></pre>\n\n<p>In the case of a simple block, all this stuff goes into the main js file (usually <code>index.js</code>) associated with the plugin.</p>\n" } ]
2020/02/11
[ "https://wordpress.stackexchange.com/questions/358428", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167299/" ]
I'm creating a block and using rich text to save some text this is my edit function. ``` edit: (props) => { const { attributes: { content, backgroundImage }, setAttributes } = props; const onImageSelect = (imageObject) => { setAttributes({ backgroundImage: imageObject.sizes.full.url }); } const onChangeContent = (newContent) => { setAttributes({ content: newContent }); }; console.log(content); return ( <div className={props.className}> <MediaUpload onSelect={onImageSelect} type="image" value={backgroundImage} render={({ open }) => ( <button onClick={open}> Upload Image! </button> )} /> <img src={backgroundImage} alt="eherh" /> <div className={'caption'}> <RichText tagName={"p"} className={'imgCtaContent'} onChange={onChangeContent} value={content} placeholder="Enter text..." /> </div> </div> ); }, ``` and this is my save function: - ``` save: (props) => { return ( <div className={props.className}> <RichText.Content tagName={"p"} value={props.attributes.content} /> </div> ); }, ``` I can see when I type into the block when I'm editing it that the console.log(content) displays the content but when I save the page the text isn't saved. Where am I going wrong?
The code from the docs is JavaScript. You have to set up Webpack and build this type of JS. So, you could use something like Create-Guten-Block to set up that build process, and then replace the contents of "block.js" with that JS from the docs. (I sure wish they would improve the docs to make things like this clearer.) Or, you could choose to filter with PHP, which instead of preventing the class from being added in the first place, processes the data saved in the database and could strip out the CSS class. (Then if you ever wanted to include the Core classes, you'd just remove your filter and they would all appear - because they're all still saved in the database.) You would do something like ``` <?php add_filter('render_block', function($block_content, $block) { // Only affect this specific block if('gutenberg-examples/example-03-editable-esnext' === $block['blockName']) { $block_content = str_replace('class="wp-block-gutenberg-examples-example-03-editable-esnext"', '', $block_content); } // Always return the content return $block_content; }, 10, 2); ?> ``` inside a custom plugin or your custom/child theme's functions.php file. Or - you could always go back and edit the block itself, in which case again you would need to set up the build process. I'm a little confused that the `save()` function doesn't actually refer to any `className`, but it looks like if you changed the `edit()` function so that it no longer had a `className`, that would likely remove the class.
358,441
<p>I now you can hide the entry-header using css but what if I want just to hide it for a specific category?</p> <pre><code>&lt;div class="entry-header"&gt; &lt;div class="entry-meta category-meta"&gt; &lt;div class="cat-links"&gt;&lt;a href="https://web.com/category/mycategory/" rel="category tag"&gt;Auspiciadores&lt;/a&gt;&lt;/div&gt; &lt;/div&gt;&lt;!-- .entry-meta --&gt; &lt;h2 class="entry-title"&gt;&lt;a href="https://web.com/2020/02/06/entry-two/"&gt;My Category&lt;/a&gt;&lt;/h2&gt; &lt;div class="entry-meta"&gt; &lt;div class="date"&gt;&lt;a href="https://web.com/2020/02/06/entry-two/" title="Entry Two"&gt;6 february 2020&lt;/a&gt; &lt;/div&gt; &lt;div class="by-author vcard author"&gt;&lt;a href="https://entry-two/author/somebody/"&gt;Somebody&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I want to aply something like the following css but just for an especific category:</p> <pre><code>.entry-header { display:none; } </code></pre> <p>EDIT:</p> <p>Can I accomplish this writing in functions.php something like this:</p> <pre><code>function prefix_category_title( $title ) { if ( is_category( 'auspiciadores' ) ) { $title = single_cat_title( '', false ); } return $title; } add_action( 'get_the_archive_title', 'prefix_category_title' ); </code></pre>
[ { "answer_id": 358396, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": true, "text": "<p>The code from the docs is JavaScript. You have to set up Webpack and build this type of JS. So, you could use something like Create-Guten-Block to set up that build process, and then replace the contents of \"block.js\" with that JS from the docs. (I sure wish they would improve the docs to make things like this clearer.)</p>\n\n<p>Or, you could choose to filter with PHP, which instead of preventing the class from being added in the first place, processes the data saved in the database and could strip out the CSS class. (Then if you ever wanted to include the Core classes, you'd just remove your filter and they would all appear - because they're all still saved in the database.) You would do something like</p>\n\n<pre><code>&lt;?php\nadd_filter('render_block', function($block_content, $block) {\n // Only affect this specific block\n if('gutenberg-examples/example-03-editable-esnext' === $block['blockName']) {\n $block_content = str_replace('class=\"wp-block-gutenberg-examples-example-03-editable-esnext\"', '', $block_content);\n }\n // Always return the content\n return $block_content;\n}, 10, 2);\n?&gt;\n</code></pre>\n\n<p>inside a custom plugin or your custom/child theme's functions.php file.</p>\n\n<p>Or - you could always go back and edit the block itself, in which case again you would need to set up the build process. I'm a little confused that the <code>save()</code> function doesn't actually refer to any <code>className</code>, but it looks like if you changed the <code>edit()</code> function so that it no longer had a <code>className</code>, that would likely remove the class.</p>\n" }, { "answer_id": 358404, "author": "Old Nick", "author_id": 122690, "author_profile": "https://wordpress.stackexchange.com/users/122690", "pm_score": 1, "selected": false, "text": "<p>Since @WebElaine didn't specify the js way, I'll add it myself. The full code to add is this:</p>\n\n<pre><code>function setBlockCustomClassName( className, blockName ) {\n return blockName === 'gutenberg-examples/example-03-editable-esnext' ? //this is the block identifier, taken from the registerBlockType\n 'new class name' : //this is class name we want to associate by default to the block, in my case it's an empty string since I don't want any class \n className;\n}\n\nwp.hooks.addFilter(\n 'blocks.getBlockDefaultClassName',\n 'gutenberg-examples/example-03-editable-esnext', //this is again the block identifier, taken from the registerBlockType\n setBlockCustomClassName\n);\n</code></pre>\n\n<p>Putting it all togheter, the full code is:</p>\n\n<pre><code>registerBlockType( 'gutenberg-examples/example-03-editable-esnext', {\n title: __( 'Example: Editable (ESNext)', 'gutenberg-examples' ),\n icon: 'universal-access-alt',\n category: 'layout',\n attributes: {\n content: {\n type: 'array',\n source: 'children',\n selector: 'p',\n },\n },\n edit: ( props ) =&gt; {\n const { attributes: { content }, setAttributes, className } = props;\n const onChangeContent = ( newContent ) =&gt; {\n setAttributes( { content: newContent } );\n };\n return (\n &lt;RichText\n tagName=\"p\"\n className={ className }\n onChange={ onChangeContent }\n value={ content }\n /&gt;\n );\n },\n save: ( props ) =&gt; {\n return &lt;RichText.Content tagName=\"p\" value={ props.attributes.content } /&gt;;\n },\n});\n//Old code ended here\nfunction setBlockCustomClassName( className, blockName ) {\n return blockName === 'gutenberg-examples/example-03-editable-esnext' ? //this is the block identifier, taken from the registerBlockType\n 'new class name' : //this is class name we want to associate by default to the block, in my case it's an empty string since I don't want any class \n className;\n}\nwp.hooks.addFilter(\n 'blocks.getBlockDefaultClassName',\n 'gutenberg-examples/example-03-editable-esnext', //this is again the block identifier, taken from the registerBlockType\n setBlockCustomClassName\n);\n</code></pre>\n\n<p>In the case of a simple block, all this stuff goes into the main js file (usually <code>index.js</code>) associated with the plugin.</p>\n" } ]
2020/02/12
[ "https://wordpress.stackexchange.com/questions/358441", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148926/" ]
I now you can hide the entry-header using css but what if I want just to hide it for a specific category? ``` <div class="entry-header"> <div class="entry-meta category-meta"> <div class="cat-links"><a href="https://web.com/category/mycategory/" rel="category tag">Auspiciadores</a></div> </div><!-- .entry-meta --> <h2 class="entry-title"><a href="https://web.com/2020/02/06/entry-two/">My Category</a></h2> <div class="entry-meta"> <div class="date"><a href="https://web.com/2020/02/06/entry-two/" title="Entry Two">6 february 2020</a> </div> <div class="by-author vcard author"><a href="https://entry-two/author/somebody/">Somebody</a> </div> </div> </div> ``` I want to aply something like the following css but just for an especific category: ``` .entry-header { display:none; } ``` EDIT: Can I accomplish this writing in functions.php something like this: ``` function prefix_category_title( $title ) { if ( is_category( 'auspiciadores' ) ) { $title = single_cat_title( '', false ); } return $title; } add_action( 'get_the_archive_title', 'prefix_category_title' ); ```
The code from the docs is JavaScript. You have to set up Webpack and build this type of JS. So, you could use something like Create-Guten-Block to set up that build process, and then replace the contents of "block.js" with that JS from the docs. (I sure wish they would improve the docs to make things like this clearer.) Or, you could choose to filter with PHP, which instead of preventing the class from being added in the first place, processes the data saved in the database and could strip out the CSS class. (Then if you ever wanted to include the Core classes, you'd just remove your filter and they would all appear - because they're all still saved in the database.) You would do something like ``` <?php add_filter('render_block', function($block_content, $block) { // Only affect this specific block if('gutenberg-examples/example-03-editable-esnext' === $block['blockName']) { $block_content = str_replace('class="wp-block-gutenberg-examples-example-03-editable-esnext"', '', $block_content); } // Always return the content return $block_content; }, 10, 2); ?> ``` inside a custom plugin or your custom/child theme's functions.php file. Or - you could always go back and edit the block itself, in which case again you would need to set up the build process. I'm a little confused that the `save()` function doesn't actually refer to any `className`, but it looks like if you changed the `edit()` function so that it no longer had a `className`, that would likely remove the class.
358,475
<p>How do you escape these two examples? <code>wc_price()</code> wraps the already escaped <code>$product_price</code> in <code>p</code> and <code>span</code> tags with currency symbol.</p> <pre><code>$product_price = $product-&gt;get_price(); &lt;p&gt;&lt;?php echo wc_price( esc_html( $product_price ) ); ?&gt;&lt;/p&gt; </code></pre> <p>The next one outputs the complete image with all attributes: <code>src</code>, <code>srcset</code>, <code>alt</code>, etc.</p> <pre><code>$product_img = $product-&gt;get_image(); &lt;?php echo $product_img; ?&gt; </code></pre>
[ { "answer_id": 358396, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": true, "text": "<p>The code from the docs is JavaScript. You have to set up Webpack and build this type of JS. So, you could use something like Create-Guten-Block to set up that build process, and then replace the contents of \"block.js\" with that JS from the docs. (I sure wish they would improve the docs to make things like this clearer.)</p>\n\n<p>Or, you could choose to filter with PHP, which instead of preventing the class from being added in the first place, processes the data saved in the database and could strip out the CSS class. (Then if you ever wanted to include the Core classes, you'd just remove your filter and they would all appear - because they're all still saved in the database.) You would do something like</p>\n\n<pre><code>&lt;?php\nadd_filter('render_block', function($block_content, $block) {\n // Only affect this specific block\n if('gutenberg-examples/example-03-editable-esnext' === $block['blockName']) {\n $block_content = str_replace('class=\"wp-block-gutenberg-examples-example-03-editable-esnext\"', '', $block_content);\n }\n // Always return the content\n return $block_content;\n}, 10, 2);\n?&gt;\n</code></pre>\n\n<p>inside a custom plugin or your custom/child theme's functions.php file.</p>\n\n<p>Or - you could always go back and edit the block itself, in which case again you would need to set up the build process. I'm a little confused that the <code>save()</code> function doesn't actually refer to any <code>className</code>, but it looks like if you changed the <code>edit()</code> function so that it no longer had a <code>className</code>, that would likely remove the class.</p>\n" }, { "answer_id": 358404, "author": "Old Nick", "author_id": 122690, "author_profile": "https://wordpress.stackexchange.com/users/122690", "pm_score": 1, "selected": false, "text": "<p>Since @WebElaine didn't specify the js way, I'll add it myself. The full code to add is this:</p>\n\n<pre><code>function setBlockCustomClassName( className, blockName ) {\n return blockName === 'gutenberg-examples/example-03-editable-esnext' ? //this is the block identifier, taken from the registerBlockType\n 'new class name' : //this is class name we want to associate by default to the block, in my case it's an empty string since I don't want any class \n className;\n}\n\nwp.hooks.addFilter(\n 'blocks.getBlockDefaultClassName',\n 'gutenberg-examples/example-03-editable-esnext', //this is again the block identifier, taken from the registerBlockType\n setBlockCustomClassName\n);\n</code></pre>\n\n<p>Putting it all togheter, the full code is:</p>\n\n<pre><code>registerBlockType( 'gutenberg-examples/example-03-editable-esnext', {\n title: __( 'Example: Editable (ESNext)', 'gutenberg-examples' ),\n icon: 'universal-access-alt',\n category: 'layout',\n attributes: {\n content: {\n type: 'array',\n source: 'children',\n selector: 'p',\n },\n },\n edit: ( props ) =&gt; {\n const { attributes: { content }, setAttributes, className } = props;\n const onChangeContent = ( newContent ) =&gt; {\n setAttributes( { content: newContent } );\n };\n return (\n &lt;RichText\n tagName=\"p\"\n className={ className }\n onChange={ onChangeContent }\n value={ content }\n /&gt;\n );\n },\n save: ( props ) =&gt; {\n return &lt;RichText.Content tagName=\"p\" value={ props.attributes.content } /&gt;;\n },\n});\n//Old code ended here\nfunction setBlockCustomClassName( className, blockName ) {\n return blockName === 'gutenberg-examples/example-03-editable-esnext' ? //this is the block identifier, taken from the registerBlockType\n 'new class name' : //this is class name we want to associate by default to the block, in my case it's an empty string since I don't want any class \n className;\n}\nwp.hooks.addFilter(\n 'blocks.getBlockDefaultClassName',\n 'gutenberg-examples/example-03-editable-esnext', //this is again the block identifier, taken from the registerBlockType\n setBlockCustomClassName\n);\n</code></pre>\n\n<p>In the case of a simple block, all this stuff goes into the main js file (usually <code>index.js</code>) associated with the plugin.</p>\n" } ]
2020/02/12
[ "https://wordpress.stackexchange.com/questions/358475", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121059/" ]
How do you escape these two examples? `wc_price()` wraps the already escaped `$product_price` in `p` and `span` tags with currency symbol. ``` $product_price = $product->get_price(); <p><?php echo wc_price( esc_html( $product_price ) ); ?></p> ``` The next one outputs the complete image with all attributes: `src`, `srcset`, `alt`, etc. ``` $product_img = $product->get_image(); <?php echo $product_img; ?> ```
The code from the docs is JavaScript. You have to set up Webpack and build this type of JS. So, you could use something like Create-Guten-Block to set up that build process, and then replace the contents of "block.js" with that JS from the docs. (I sure wish they would improve the docs to make things like this clearer.) Or, you could choose to filter with PHP, which instead of preventing the class from being added in the first place, processes the data saved in the database and could strip out the CSS class. (Then if you ever wanted to include the Core classes, you'd just remove your filter and they would all appear - because they're all still saved in the database.) You would do something like ``` <?php add_filter('render_block', function($block_content, $block) { // Only affect this specific block if('gutenberg-examples/example-03-editable-esnext' === $block['blockName']) { $block_content = str_replace('class="wp-block-gutenberg-examples-example-03-editable-esnext"', '', $block_content); } // Always return the content return $block_content; }, 10, 2); ?> ``` inside a custom plugin or your custom/child theme's functions.php file. Or - you could always go back and edit the block itself, in which case again you would need to set up the build process. I'm a little confused that the `save()` function doesn't actually refer to any `className`, but it looks like if you changed the `edit()` function so that it no longer had a `className`, that would likely remove the class.
358,541
<p>Using an example given here: <a href="https://rudrastyh.com/gutenberg/remove-default-blocks.html" rel="nofollow noreferrer">enter link description here</a> I've successfully been able to restrict the block types available globally or by post type (eg: page). But what I really would like to do is restrict the the block types by page template. I have tried using <code>if ( is_page_template('page-home.php') ) {...}</code> but with no joy. It will be apparant from the code below, but I am using ACF custom blocks. The blocks themselves are working fine. So currently I have the following in my functions.php file:</p> <pre><code>function my_allowed_block_types( $allowed_blocks, $post ) { // works on all content $allowed_blocks = array( 'core/image', 'core/paragraph', 'core/heading', 'core/list' ); // works for all pages but too general for what I want to do if( $post-&gt;post_type === 'page' ) { $allowed_blocks= array( 'acf/homepage' ); } // Intended to restrict to just one block on my homepage template but does not if ( is_page_template('page-home.php') ) { $allowed_blocks= array( 'acf/homepage' ); } </code></pre>
[ { "answer_id": 358510, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 1, "selected": false, "text": "<p>You can use FTP to edit edit your .htaccess file, which should be found in the root WordPress install. </p>\n\n<p>For example...</p>\n\n<p><code>Redirect 301 /old-url /some-new-url</code></p>\n\n<p>Put the old page first and just a / for the homepage second.</p>\n\n<p>Note: Make your edits after the <code># END WordPress</code> line</p>\n\n<p>Note 2: There are a ton of plugins that can help with redirects but since this site is about coding I suggest the .htaccess way, which is what a plugin would do for you</p>\n" }, { "answer_id": 360050, "author": "Bikram", "author_id": 145504, "author_profile": "https://wordpress.stackexchange.com/users/145504", "pm_score": 0, "selected": false, "text": "<p>Since you use Yoast, you can change the redirect on your Yoast Redirect Manager. Edit the redirect you created on deleting your post. Replace the current destination to your homepage URL.</p>\n\n<p><strong>Note</strong>: Your current browser might have already cached your URL so the changes will not be identified on your current browser. Clear your browser cache or check it on another browser or other device. Your new redirection will reflect immediately.</p>\n\n<p>You can also use <code>.htaccess</code> or PHP for redirection. But you already got the easy solution with Yoast Redirect manager.</p>\n" } ]
2020/02/13
[ "https://wordpress.stackexchange.com/questions/358541", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51930/" ]
Using an example given here: [enter link description here](https://rudrastyh.com/gutenberg/remove-default-blocks.html) I've successfully been able to restrict the block types available globally or by post type (eg: page). But what I really would like to do is restrict the the block types by page template. I have tried using `if ( is_page_template('page-home.php') ) {...}` but with no joy. It will be apparant from the code below, but I am using ACF custom blocks. The blocks themselves are working fine. So currently I have the following in my functions.php file: ``` function my_allowed_block_types( $allowed_blocks, $post ) { // works on all content $allowed_blocks = array( 'core/image', 'core/paragraph', 'core/heading', 'core/list' ); // works for all pages but too general for what I want to do if( $post->post_type === 'page' ) { $allowed_blocks= array( 'acf/homepage' ); } // Intended to restrict to just one block on my homepage template but does not if ( is_page_template('page-home.php') ) { $allowed_blocks= array( 'acf/homepage' ); } ```
You can use FTP to edit edit your .htaccess file, which should be found in the root WordPress install. For example... `Redirect 301 /old-url /some-new-url` Put the old page first and just a / for the homepage second. Note: Make your edits after the `# END WordPress` line Note 2: There are a ton of plugins that can help with redirects but since this site is about coding I suggest the .htaccess way, which is what a plugin would do for you
358,558
<p>I wrote a shortcode to display all my jobs. When there are no jobs, I want to display a message instead of the available jobs. I used an else-statement to do this, but when the message shows, it shows on top of the page instead of the place where I added the shortcode.</p> <p><strong>My code:</strong></p> <pre><code>function dfib_jobs_shortcode( $atts ) { ob_start(); $query = new WP_Query( array( 'post_type' =&gt; 'jobpost', 'posts_per_page' =&gt; -1, 'order' =&gt; 'ASC', 'orderby' =&gt; 'rand', ) ); ?&gt; &lt;div class="vacatures__wrapper"&gt; &lt;?php if ( $query-&gt;have_posts() ) { ?&gt; &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; &lt;div class="vacature__item"&gt; &lt;h4 class="vacature__title"&gt;&lt;?php the_title() ?&gt;&lt;/h4&gt; &lt;?php if ( has_excerpt() ) { the_excerpt(); } else { the_content(); } ?&gt; &lt;a class="vacature__btn" href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php _e( 'meer info', 'vdp' ) ?&gt;&lt;/a&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;div class="vacature__item spontaan"&gt; &lt;h4 class="vacature__title"&gt;&lt;?php _e( 'Spontaan solliciteren?', 'vdp' ) ?&gt;&lt;/h4&gt; &lt;a class="vacature__btn" href="&lt;?php _e( '/spontaan-solliciteren', 'vdp' ) ?&gt;"&gt;&lt;?php _e( 'solliciteren', 'vdp' ) ?&gt;&lt;/a&gt; &lt;/div&gt; &lt;?php wp_reset_postdata(); $myvariable = ob_get_clean(); return $myvariable; } else { ?&gt; &lt;div class="vacature__item spontaan"&gt; &lt;h4 class="vacature__title"&gt;&lt;?php _e( 'Momenteel zijn er geen vacatures!', 'vdp' ) ?&gt;&lt;/h4&gt; &lt;a class="vacature__btn" href="&lt;?php _e( '/spontaan-solliciteren', 'vdp' ) ?&gt;"&gt;&lt;?php _e( 'Spontaan solliciteren', 'vdp' ) ?&gt;&lt;/a&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;?php } add_shortcode( 'vacatures', 'dfib_jobs_shortcode' ); </code></pre>
[ { "answer_id": 358559, "author": "GarethTF", "author_id": 181549, "author_profile": "https://wordpress.stackexchange.com/users/181549", "pm_score": 0, "selected": false, "text": "<p>You can add another if around the code such as:</p>\n\n<pre><code>$total_posts = $query-&gt;found_posts;\nif( $total_posts &gt; 0 ) {\n // your code\n} else {\n echo 'nothing found here';\n}\n</code></pre>\n\n<p>found_posts is one of the properties you can view from a WP_query (more info <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#properties\" rel=\"nofollow noreferrer\">here</a>)</p>\n" }, { "answer_id": 358560, "author": "Thessa Verbruggen", "author_id": 167092, "author_profile": "https://wordpress.stackexchange.com/users/167092", "pm_score": 2, "selected": true, "text": "<p><strong>Answer</strong></p>\n\n<p>I found the answer, thanks to a comment and after some digging myself:</p>\n\n<pre><code>function dfib_jobs_shortcode( $atts ) {\nob_start();\n\n$query = new WP_Query( array(\n 'post_type' =&gt; 'jobpost',\n 'posts_per_page' =&gt; -1,\n 'order' =&gt; 'ASC',\n 'orderby' =&gt; 'rand',\n) );\n?&gt;\n&lt;div class=\"vacatures__wrapper\"&gt;\n&lt;?php if ( $query-&gt;have_posts() ) { ?&gt;\n &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n &lt;div class=\"vacature__item\"&gt;\n &lt;h4 class=\"vacature__title\"&gt;&lt;?php the_title() ?&gt;&lt;/h4&gt;\n &lt;?php if ( has_excerpt() ) { \n the_excerpt();\n } else {\n the_content();\n } ?&gt;\n &lt;a class=\"vacature__btn\" href=\"&lt;?php the_permalink() ?&gt;\"&gt;&lt;?php _e( 'meer info', 'vdp' ) ?&gt;&lt;/a&gt;\n &lt;/div&gt;\n &lt;?php endwhile; ?&gt;\n &lt;div class=\"vacature__item spontaan\"&gt;\n &lt;h4 class=\"vacature__title\"&gt;&lt;?php _e( 'Spontaan solliciteren?', 'vdp' ) ?&gt;&lt;/h4&gt;\n &lt;a class=\"vacature__btn\" href=\"&lt;?php _e( '/spontaan-solliciteren', 'vdp' ) ?&gt;\"&gt;&lt;?php _e( 'solliciteren', 'vdp' ) ?&gt;&lt;/a&gt;\n &lt;/div&gt;\n &lt;?php wp_reset_postdata(); ?&gt;\n&lt;?php\n} else {\n ?&gt;\n &lt;div class=\"vacature__item spontaan\"&gt;\n &lt;h4 class=\"vacature__title\"&gt;&lt;?php _e( 'Momenteel zijn er geen vacatures!', 'vdp' ) ?&gt;&lt;/h4&gt;\n &lt;a class=\"vacature__btn\" href=\"&lt;?php _e( '/spontaan-solliciteren', 'vdp' ) ?&gt;\"&gt;&lt;?php _e( 'Spontaan solliciteren', 'vdp' ) ?&gt;&lt;/a&gt;\n &lt;/div&gt;\n &lt;?php\n} ?&gt;\n&lt;/div&gt;\n&lt;?php $myvariable = ob_get_clean();\nreturn $myvariable;\n}\nadd_shortcode( 'vacatures', 'dfib_jobs_shortcode' );\n</code></pre>\n" } ]
2020/02/13
[ "https://wordpress.stackexchange.com/questions/358558", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167092/" ]
I wrote a shortcode to display all my jobs. When there are no jobs, I want to display a message instead of the available jobs. I used an else-statement to do this, but when the message shows, it shows on top of the page instead of the place where I added the shortcode. **My code:** ``` function dfib_jobs_shortcode( $atts ) { ob_start(); $query = new WP_Query( array( 'post_type' => 'jobpost', 'posts_per_page' => -1, 'order' => 'ASC', 'orderby' => 'rand', ) ); ?> <div class="vacatures__wrapper"> <?php if ( $query->have_posts() ) { ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <div class="vacature__item"> <h4 class="vacature__title"><?php the_title() ?></h4> <?php if ( has_excerpt() ) { the_excerpt(); } else { the_content(); } ?> <a class="vacature__btn" href="<?php the_permalink() ?>"><?php _e( 'meer info', 'vdp' ) ?></a> </div> <?php endwhile; ?> <div class="vacature__item spontaan"> <h4 class="vacature__title"><?php _e( 'Spontaan solliciteren?', 'vdp' ) ?></h4> <a class="vacature__btn" href="<?php _e( '/spontaan-solliciteren', 'vdp' ) ?>"><?php _e( 'solliciteren', 'vdp' ) ?></a> </div> <?php wp_reset_postdata(); $myvariable = ob_get_clean(); return $myvariable; } else { ?> <div class="vacature__item spontaan"> <h4 class="vacature__title"><?php _e( 'Momenteel zijn er geen vacatures!', 'vdp' ) ?></h4> <a class="vacature__btn" href="<?php _e( '/spontaan-solliciteren', 'vdp' ) ?>"><?php _e( 'Spontaan solliciteren', 'vdp' ) ?></a> </div> <?php } ?> </div> <?php } add_shortcode( 'vacatures', 'dfib_jobs_shortcode' ); ```
**Answer** I found the answer, thanks to a comment and after some digging myself: ``` function dfib_jobs_shortcode( $atts ) { ob_start(); $query = new WP_Query( array( 'post_type' => 'jobpost', 'posts_per_page' => -1, 'order' => 'ASC', 'orderby' => 'rand', ) ); ?> <div class="vacatures__wrapper"> <?php if ( $query->have_posts() ) { ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <div class="vacature__item"> <h4 class="vacature__title"><?php the_title() ?></h4> <?php if ( has_excerpt() ) { the_excerpt(); } else { the_content(); } ?> <a class="vacature__btn" href="<?php the_permalink() ?>"><?php _e( 'meer info', 'vdp' ) ?></a> </div> <?php endwhile; ?> <div class="vacature__item spontaan"> <h4 class="vacature__title"><?php _e( 'Spontaan solliciteren?', 'vdp' ) ?></h4> <a class="vacature__btn" href="<?php _e( '/spontaan-solliciteren', 'vdp' ) ?>"><?php _e( 'solliciteren', 'vdp' ) ?></a> </div> <?php wp_reset_postdata(); ?> <?php } else { ?> <div class="vacature__item spontaan"> <h4 class="vacature__title"><?php _e( 'Momenteel zijn er geen vacatures!', 'vdp' ) ?></h4> <a class="vacature__btn" href="<?php _e( '/spontaan-solliciteren', 'vdp' ) ?>"><?php _e( 'Spontaan solliciteren', 'vdp' ) ?></a> </div> <?php } ?> </div> <?php $myvariable = ob_get_clean(); return $myvariable; } add_shortcode( 'vacatures', 'dfib_jobs_shortcode' ); ```
358,571
<p>I use this code:</p> <pre><code>if ( ! function_exists( 'WPScripts_enqueue' ) ) { function WPScripts_enqueue() { // Removing default jQuery wp_deregister_script( 'jquery' ); // Enqueue the new jQuery wp_enqueue_script('jquery', 'https://code.jquery.com/jquery-3.2.1.slim.min.js', false, '3.2.1', false); // Enqueue custom Bootstrap file wp_enqueue_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.css', array(), false, 'all'); } } add_action('wp_enqueue_scripts', 'WPScripts_enqueue'); </code></pre> <p>however, wp still load jquery from wp core:</p> <p><a href="https://developers.google.com/speed/pagespeed/insights/?hl=TR&amp;url=http%3A%2F%2Fwww.migrate2.deniz-tasarim.site%2Fhomepage%2F&amp;tab=desktop" rel="nofollow noreferrer">https://developers.google.com/speed/pagespeed/insights/?hl=TR&amp;url=http%3A%2F%2Fwww.migrate2.deniz-tasarim.site%2Fhomepage%2F&amp;tab=desktop</a></p> <p><a href="https://i.ibb.co/qxhCY6R/image.png" rel="nofollow noreferrer">https://i.ibb.co/qxhCY6R/image.png</a></p>
[ { "answer_id": 358593, "author": "Sonali Yewle", "author_id": 178505, "author_profile": "https://wordpress.stackexchange.com/users/178505", "pm_score": -1, "selected": false, "text": "<p>You have to first dequeue the script first &amp; then deregister the script as given as bellow</p>\n\n<pre><code> wp_dequeue_script( 'jquery');\n\n wp_deregister_script(‘jquery’);\n</code></pre>\n\n<p>Try this!!</p>\n" }, { "answer_id": 358629, "author": "Sonali Yewle", "author_id": 178505, "author_profile": "https://wordpress.stackexchange.com/users/178505", "pm_score": 1, "selected": false, "text": "<p><strong>Use the Following sequence to override jquery</strong><br>\nInstall latest jQuery version 3.4.1.\nUpdate the following sequence of code and try!!!!</p>\n\n<pre><code> wp_deregister_script('jquery');\n wp_register_script('jquery',(\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"), \n false);\n wp_enqueue_script('jquery');\n</code></pre>\n\n<p>I hope it will help you!!!</p>\n" }, { "answer_id": 358633, "author": "Patryk Parcheta", "author_id": 181863, "author_profile": "https://wordpress.stackexchange.com/users/181863", "pm_score": 0, "selected": false, "text": "<p>Add priority to add_action. </p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'WPScripts_enqueue', 999);\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'WPScripts_enqueue', -1);\n</code></pre>\n" }, { "answer_id": 391246, "author": "Everaldo Matias", "author_id": 120927, "author_profile": "https://wordpress.stackexchange.com/users/120927", "pm_score": 0, "selected": false, "text": "<p>Second documentation example (<a href=\"https://developer.wordpress.org/reference/functions/wp_dequeue_script/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_dequeue_script/</a>), use hook <code>wp_print_scripts</code> with priority <code>100</code>. Like this:</p>\n<pre><code>function wpdocs_dequeue_script() {\n wp_dequeue_script( 'jquery-ui-core' );\n}\n\nadd_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 );\n</code></pre>\n" } ]
2020/02/13
[ "https://wordpress.stackexchange.com/questions/358571", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/172430/" ]
I use this code: ``` if ( ! function_exists( 'WPScripts_enqueue' ) ) { function WPScripts_enqueue() { // Removing default jQuery wp_deregister_script( 'jquery' ); // Enqueue the new jQuery wp_enqueue_script('jquery', 'https://code.jquery.com/jquery-3.2.1.slim.min.js', false, '3.2.1', false); // Enqueue custom Bootstrap file wp_enqueue_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.css', array(), false, 'all'); } } add_action('wp_enqueue_scripts', 'WPScripts_enqueue'); ``` however, wp still load jquery from wp core: <https://developers.google.com/speed/pagespeed/insights/?hl=TR&url=http%3A%2F%2Fwww.migrate2.deniz-tasarim.site%2Fhomepage%2F&tab=desktop> <https://i.ibb.co/qxhCY6R/image.png>
**Use the Following sequence to override jquery** Install latest jQuery version 3.4.1. Update the following sequence of code and try!!!! ``` wp_deregister_script('jquery'); wp_register_script('jquery',("https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"), false); wp_enqueue_script('jquery'); ``` I hope it will help you!!!
358,577
<p>I am trying to show post thumbnail with the_post_thumbnail() function but the function automatically set image size inline CSS that why my CSS is not working properly.</p>
[ { "answer_id": 358593, "author": "Sonali Yewle", "author_id": 178505, "author_profile": "https://wordpress.stackexchange.com/users/178505", "pm_score": -1, "selected": false, "text": "<p>You have to first dequeue the script first &amp; then deregister the script as given as bellow</p>\n\n<pre><code> wp_dequeue_script( 'jquery');\n\n wp_deregister_script(‘jquery’);\n</code></pre>\n\n<p>Try this!!</p>\n" }, { "answer_id": 358629, "author": "Sonali Yewle", "author_id": 178505, "author_profile": "https://wordpress.stackexchange.com/users/178505", "pm_score": 1, "selected": false, "text": "<p><strong>Use the Following sequence to override jquery</strong><br>\nInstall latest jQuery version 3.4.1.\nUpdate the following sequence of code and try!!!!</p>\n\n<pre><code> wp_deregister_script('jquery');\n wp_register_script('jquery',(\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"), \n false);\n wp_enqueue_script('jquery');\n</code></pre>\n\n<p>I hope it will help you!!!</p>\n" }, { "answer_id": 358633, "author": "Patryk Parcheta", "author_id": 181863, "author_profile": "https://wordpress.stackexchange.com/users/181863", "pm_score": 0, "selected": false, "text": "<p>Add priority to add_action. </p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'WPScripts_enqueue', 999);\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'WPScripts_enqueue', -1);\n</code></pre>\n" }, { "answer_id": 391246, "author": "Everaldo Matias", "author_id": 120927, "author_profile": "https://wordpress.stackexchange.com/users/120927", "pm_score": 0, "selected": false, "text": "<p>Second documentation example (<a href=\"https://developer.wordpress.org/reference/functions/wp_dequeue_script/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_dequeue_script/</a>), use hook <code>wp_print_scripts</code> with priority <code>100</code>. Like this:</p>\n<pre><code>function wpdocs_dequeue_script() {\n wp_dequeue_script( 'jquery-ui-core' );\n}\n\nadd_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 );\n</code></pre>\n" } ]
2020/02/13
[ "https://wordpress.stackexchange.com/questions/358577", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/182666/" ]
I am trying to show post thumbnail with the\_post\_thumbnail() function but the function automatically set image size inline CSS that why my CSS is not working properly.
**Use the Following sequence to override jquery** Install latest jQuery version 3.4.1. Update the following sequence of code and try!!!! ``` wp_deregister_script('jquery'); wp_register_script('jquery',("https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"), false); wp_enqueue_script('jquery'); ``` I hope it will help you!!!
358,598
<p>I just installed a wordpress from my c panel, when i tried login to wp-admin it shows an unknown page instead of wp-admin. please somebody can help ??<a href="https://i.stack.imgur.com/byOIv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/byOIv.png" alt="enter image description here"></a> </p>
[ { "answer_id": 358593, "author": "Sonali Yewle", "author_id": 178505, "author_profile": "https://wordpress.stackexchange.com/users/178505", "pm_score": -1, "selected": false, "text": "<p>You have to first dequeue the script first &amp; then deregister the script as given as bellow</p>\n\n<pre><code> wp_dequeue_script( 'jquery');\n\n wp_deregister_script(‘jquery’);\n</code></pre>\n\n<p>Try this!!</p>\n" }, { "answer_id": 358629, "author": "Sonali Yewle", "author_id": 178505, "author_profile": "https://wordpress.stackexchange.com/users/178505", "pm_score": 1, "selected": false, "text": "<p><strong>Use the Following sequence to override jquery</strong><br>\nInstall latest jQuery version 3.4.1.\nUpdate the following sequence of code and try!!!!</p>\n\n<pre><code> wp_deregister_script('jquery');\n wp_register_script('jquery',(\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"), \n false);\n wp_enqueue_script('jquery');\n</code></pre>\n\n<p>I hope it will help you!!!</p>\n" }, { "answer_id": 358633, "author": "Patryk Parcheta", "author_id": 181863, "author_profile": "https://wordpress.stackexchange.com/users/181863", "pm_score": 0, "selected": false, "text": "<p>Add priority to add_action. </p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'WPScripts_enqueue', 999);\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'WPScripts_enqueue', -1);\n</code></pre>\n" }, { "answer_id": 391246, "author": "Everaldo Matias", "author_id": 120927, "author_profile": "https://wordpress.stackexchange.com/users/120927", "pm_score": 0, "selected": false, "text": "<p>Second documentation example (<a href=\"https://developer.wordpress.org/reference/functions/wp_dequeue_script/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_dequeue_script/</a>), use hook <code>wp_print_scripts</code> with priority <code>100</code>. Like this:</p>\n<pre><code>function wpdocs_dequeue_script() {\n wp_dequeue_script( 'jquery-ui-core' );\n}\n\nadd_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 );\n</code></pre>\n" } ]
2020/02/13
[ "https://wordpress.stackexchange.com/questions/358598", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/182676/" ]
I just installed a wordpress from my c panel, when i tried login to wp-admin it shows an unknown page instead of wp-admin. please somebody can help ??[![enter image description here](https://i.stack.imgur.com/byOIv.png)](https://i.stack.imgur.com/byOIv.png)
**Use the Following sequence to override jquery** Install latest jQuery version 3.4.1. Update the following sequence of code and try!!!! ``` wp_deregister_script('jquery'); wp_register_script('jquery',("https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"), false); wp_enqueue_script('jquery'); ``` I hope it will help you!!!
358,682
<p>I am working, on a code, where i need to loop Through all posts of a given author, and then for each post of that author, count the number of media attachments, the post has and then echo it.</p> <p>I am able to loop Through posts, and it works as expected, but then i want to count the number of attachments of each post, where i fail, please help.</p> <pre><code>$author_posts = get_posts( array('author' =&gt; $author_id, 'numberposts' =&gt; -1, 'post_type'=&gt; array('post','download', 'attachment' ), 'post_status'=&gt; array('publish','privatised'), )); </code></pre> <p>This was the orignal loop.</p> <p>Below is the code, here the words are counted as expected, comments are counted as expected too. For simplicity in prefered not to include the echo portion</p> <pre><code> foreach ( $author_posts as $post ) { $View_Count = absint( get_post_meta( $post-&gt;ID, 'Creation_Views', true ) ); $Word_Count = str_word_count( strip_tags( get_post_field( 'post_content', $post-&gt;ID ))); $Image_Count = count( get_attached_media( 'image', $post-&gt;ID ) ); $Comment_Count = get_comments_number($post-&gt;ID) ; </code></pre> <p>Please help, the $Image_Count, always gives 0, regardless of which post i check. I have over 500 posts, and it shows 0 for all of them, while all of them atleast have 1 attachment </p>
[ { "answer_id": 358593, "author": "Sonali Yewle", "author_id": 178505, "author_profile": "https://wordpress.stackexchange.com/users/178505", "pm_score": -1, "selected": false, "text": "<p>You have to first dequeue the script first &amp; then deregister the script as given as bellow</p>\n\n<pre><code> wp_dequeue_script( 'jquery');\n\n wp_deregister_script(‘jquery’);\n</code></pre>\n\n<p>Try this!!</p>\n" }, { "answer_id": 358629, "author": "Sonali Yewle", "author_id": 178505, "author_profile": "https://wordpress.stackexchange.com/users/178505", "pm_score": 1, "selected": false, "text": "<p><strong>Use the Following sequence to override jquery</strong><br>\nInstall latest jQuery version 3.4.1.\nUpdate the following sequence of code and try!!!!</p>\n\n<pre><code> wp_deregister_script('jquery');\n wp_register_script('jquery',(\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"), \n false);\n wp_enqueue_script('jquery');\n</code></pre>\n\n<p>I hope it will help you!!!</p>\n" }, { "answer_id": 358633, "author": "Patryk Parcheta", "author_id": 181863, "author_profile": "https://wordpress.stackexchange.com/users/181863", "pm_score": 0, "selected": false, "text": "<p>Add priority to add_action. </p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'WPScripts_enqueue', 999);\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'WPScripts_enqueue', -1);\n</code></pre>\n" }, { "answer_id": 391246, "author": "Everaldo Matias", "author_id": 120927, "author_profile": "https://wordpress.stackexchange.com/users/120927", "pm_score": 0, "selected": false, "text": "<p>Second documentation example (<a href=\"https://developer.wordpress.org/reference/functions/wp_dequeue_script/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_dequeue_script/</a>), use hook <code>wp_print_scripts</code> with priority <code>100</code>. Like this:</p>\n<pre><code>function wpdocs_dequeue_script() {\n wp_dequeue_script( 'jquery-ui-core' );\n}\n\nadd_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 );\n</code></pre>\n" } ]
2020/02/14
[ "https://wordpress.stackexchange.com/questions/358682", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/166927/" ]
I am working, on a code, where i need to loop Through all posts of a given author, and then for each post of that author, count the number of media attachments, the post has and then echo it. I am able to loop Through posts, and it works as expected, but then i want to count the number of attachments of each post, where i fail, please help. ``` $author_posts = get_posts( array('author' => $author_id, 'numberposts' => -1, 'post_type'=> array('post','download', 'attachment' ), 'post_status'=> array('publish','privatised'), )); ``` This was the orignal loop. Below is the code, here the words are counted as expected, comments are counted as expected too. For simplicity in prefered not to include the echo portion ``` foreach ( $author_posts as $post ) { $View_Count = absint( get_post_meta( $post->ID, 'Creation_Views', true ) ); $Word_Count = str_word_count( strip_tags( get_post_field( 'post_content', $post->ID ))); $Image_Count = count( get_attached_media( 'image', $post->ID ) ); $Comment_Count = get_comments_number($post->ID) ; ``` Please help, the $Image\_Count, always gives 0, regardless of which post i check. I have over 500 posts, and it shows 0 for all of them, while all of them atleast have 1 attachment
**Use the Following sequence to override jquery** Install latest jQuery version 3.4.1. Update the following sequence of code and try!!!! ``` wp_deregister_script('jquery'); wp_register_script('jquery',("https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"), false); wp_enqueue_script('jquery'); ``` I hope it will help you!!!
358,708
<p>I have an issue where <code>is_user_logged_in()</code> appears to alternate between being true and false.</p> <p>Additionally, <code>get_current_user_id()</code> gives the correct user ID if <code>is_user_logged_in()</code> is true.</p> <p>Here's my code: </p> <p>.htaccess:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} -s RewriteRule ^wp-content/uploads/(.*)$ file-access.php?file=$1 [QSA,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>file-access.php:</p> <pre><code>require_once('wp-load.php'); if ( is_user_logged_in() ) { // User is logged in, proceed. } else { // User is a guest, block. } </code></pre> <p>I've verified the alternating status and user id using some error logging in the <code>file-access.php</code> conditionals.</p> <p>Do I need to call something other than wp-load.php perhaps? Just seems strange to me that it alternates between true and false, rather than always being false...</p> <p>Edit to add: I also had an issue where one of my files I was testing with wasn't uploaded as the https version which caused issues.</p>
[ { "answer_id": 358814, "author": "Mike", "author_id": 62621, "author_profile": "https://wordpress.stackexchange.com/users/62621", "pm_score": 0, "selected": false, "text": "<p>The file that would normally be called to kick off the Wordpress setup is wp-blog-header.php so maybe try swapping out <code>wp-load.php</code> for <code>wp-blog-header.php</code> in your code then re-test</p>\n" }, { "answer_id": 358913, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 3, "selected": true, "text": "<p>I've run your code and it works fine to me except for the inclusion in file-access.php:</p>\n\n<p><code>require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');</code> \nenable debug to see if there are errors depending on other issues and not regarding these specific code lines.</p>\n\n<p>But.. as per WP documentation: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request\" rel=\"nofollow noreferrer\">actions reference</a> the earlier action hook where the authentication process is completed and cookies are set is <code>init</code> as suggested in <a href=\"https://wordpress.stackexchange.com/users/30852/mohsin\">@Mohsin</a> comment so I suggest to use this code in <em>file-access.php</em></p>\n\n<pre><code>/* you probably don't need a theme */ \ndefine( 'WP_USE_THEMES', false ); \n\n/* defining a constant here allows you to exit functions when not needed */\ndefine('FROM_EXTERNAL_FILE',true);\n\n/* unless you've renamed your wp-content folder this path will always point to wp-load.php even in subfolders installations */\nrequire_once(explode(\"wp-content\", __FILE__)[0] . \"wp-load.php\");\n</code></pre>\n\n<p>and move the check in your file functions.php which gets loaded with the whole WP environment by <em>wp-load.php</em></p>\n\n<pre><code>function is_logged_function(){\n if ( !defined ('FROM_EXTERNAL_FILE') )\n return;\n if ( is_user_logged_in()){\n echo \"logged\";\n echo get_current_user_id();\n }\n else{\n echo \"not logged\";\n }\n}\nadd_action('init', 'is_logged_function');\n</code></pre>\n" } ]
2020/02/15
[ "https://wordpress.stackexchange.com/questions/358708", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109355/" ]
I have an issue where `is_user_logged_in()` appears to alternate between being true and false. Additionally, `get_current_user_id()` gives the correct user ID if `is_user_logged_in()` is true. Here's my code: .htaccess: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} -s RewriteRule ^wp-content/uploads/(.*)$ file-access.php?file=$1 [QSA,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` file-access.php: ``` require_once('wp-load.php'); if ( is_user_logged_in() ) { // User is logged in, proceed. } else { // User is a guest, block. } ``` I've verified the alternating status and user id using some error logging in the `file-access.php` conditionals. Do I need to call something other than wp-load.php perhaps? Just seems strange to me that it alternates between true and false, rather than always being false... Edit to add: I also had an issue where one of my files I was testing with wasn't uploaded as the https version which caused issues.
I've run your code and it works fine to me except for the inclusion in file-access.php: `require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');` enable debug to see if there are errors depending on other issues and not regarding these specific code lines. But.. as per WP documentation: [actions reference](https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request) the earlier action hook where the authentication process is completed and cookies are set is `init` as suggested in [@Mohsin](https://wordpress.stackexchange.com/users/30852/mohsin) comment so I suggest to use this code in *file-access.php* ``` /* you probably don't need a theme */ define( 'WP_USE_THEMES', false ); /* defining a constant here allows you to exit functions when not needed */ define('FROM_EXTERNAL_FILE',true); /* unless you've renamed your wp-content folder this path will always point to wp-load.php even in subfolders installations */ require_once(explode("wp-content", __FILE__)[0] . "wp-load.php"); ``` and move the check in your file functions.php which gets loaded with the whole WP environment by *wp-load.php* ``` function is_logged_function(){ if ( !defined ('FROM_EXTERNAL_FILE') ) return; if ( is_user_logged_in()){ echo "logged"; echo get_current_user_id(); } else{ echo "not logged"; } } add_action('init', 'is_logged_function'); ```
358,722
<p>I am working with Wordpress Multisite (with sub-directory structure). Everything works fine instead of Wordpress pages. When I publish a page and I try to visit it, it redirects to the main multisite.</p> <p>So for example, if the page is in this path:</p> <p><a href="https://example.com/en-us/my-new-page/" rel="nofollow noreferrer">https://example.com/en-us/my-new-page/</a></p> <p>it automatically redirects to:</p> <p><a href="https://example.com/en-us/" rel="nofollow noreferrer">https://example.com/en-us/</a></p> <p>Or another example, if the page is in this path:</p> <p><a href="https://example.com/es-es/my-really-new-page/" rel="nofollow noreferrer">https://example.com/es-es/my-really-new-page/</a></p> <p>it automatically redirects to:</p> <p><a href="https://example.com/es-es/" rel="nofollow noreferrer">https://example.com/es-es/</a></p> <p>I am using a plugin called Custom Permalinks to make posts URLs look nicer. I am using nginx as web server. I am developing the site, so currently on an IP, not a domain. I am redirecting the current root domain <a href="https://example.com/" rel="nofollow noreferrer">https://example.com/</a> to the main multisite path <a href="https://example.com/en-us/" rel="nofollow noreferrer">https://example.com/en-us/</a> with Redirection plugin.</p> <p>This is my nginx conf file:</p> <pre><code>upstream php-handler-http { server 127.0.0.1:9000; #server unix:/var/run/php5-fpm.sock; } map $http_host $blogid { default 0; include /var/www/html/wp-content/uploads/nginx-helper/map.conf; } server { listen 80 default_server; server_name 123.123.123.123; root /var/www/html/; index index.php; access_log /var/log/nginx/wordpress_http_access.log combined; error_log /var/log/nginx/wordpress_http_error.log; # set max upload size client_max_body_size 2G; fastcgi_buffers 64 4K; if (!-e $request_filename) { rewrite /wp-admin$ $scheme://$host$request_uri/ permanent; rewrite ^(/[^/]+)?(/wp-.*) $2 last; rewrite ^(/[^/]+)?(/.*\.php) $2 last; } location / { try_files $uri $uri/ /index.php?$args ; } location ~ \.php(?:$|/) { fastcgi_split_path_info ^(.+\.php)(/.+)$; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_pass php-handler-http; fastcgi_read_timeout 600; } location = /favicon.ico { log_not_found off; access_log off; } location = /robots.txt { allow all; log_not_found off; access_log off; } location ~* \.(htaccess|htpasswd) { deny all; } # set long EXPIRES header on static assets location ~* \.(?:jpg|jpeg|gif|bmp|ico|png|css|js|swf)$ { expires 24h; access_log off; } } </code></pre>
[ { "answer_id": 358814, "author": "Mike", "author_id": 62621, "author_profile": "https://wordpress.stackexchange.com/users/62621", "pm_score": 0, "selected": false, "text": "<p>The file that would normally be called to kick off the Wordpress setup is wp-blog-header.php so maybe try swapping out <code>wp-load.php</code> for <code>wp-blog-header.php</code> in your code then re-test</p>\n" }, { "answer_id": 358913, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 3, "selected": true, "text": "<p>I've run your code and it works fine to me except for the inclusion in file-access.php:</p>\n\n<p><code>require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');</code> \nenable debug to see if there are errors depending on other issues and not regarding these specific code lines.</p>\n\n<p>But.. as per WP documentation: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request\" rel=\"nofollow noreferrer\">actions reference</a> the earlier action hook where the authentication process is completed and cookies are set is <code>init</code> as suggested in <a href=\"https://wordpress.stackexchange.com/users/30852/mohsin\">@Mohsin</a> comment so I suggest to use this code in <em>file-access.php</em></p>\n\n<pre><code>/* you probably don't need a theme */ \ndefine( 'WP_USE_THEMES', false ); \n\n/* defining a constant here allows you to exit functions when not needed */\ndefine('FROM_EXTERNAL_FILE',true);\n\n/* unless you've renamed your wp-content folder this path will always point to wp-load.php even in subfolders installations */\nrequire_once(explode(\"wp-content\", __FILE__)[0] . \"wp-load.php\");\n</code></pre>\n\n<p>and move the check in your file functions.php which gets loaded with the whole WP environment by <em>wp-load.php</em></p>\n\n<pre><code>function is_logged_function(){\n if ( !defined ('FROM_EXTERNAL_FILE') )\n return;\n if ( is_user_logged_in()){\n echo \"logged\";\n echo get_current_user_id();\n }\n else{\n echo \"not logged\";\n }\n}\nadd_action('init', 'is_logged_function');\n</code></pre>\n" } ]
2020/02/15
[ "https://wordpress.stackexchange.com/questions/358722", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/49659/" ]
I am working with Wordpress Multisite (with sub-directory structure). Everything works fine instead of Wordpress pages. When I publish a page and I try to visit it, it redirects to the main multisite. So for example, if the page is in this path: <https://example.com/en-us/my-new-page/> it automatically redirects to: <https://example.com/en-us/> Or another example, if the page is in this path: <https://example.com/es-es/my-really-new-page/> it automatically redirects to: <https://example.com/es-es/> I am using a plugin called Custom Permalinks to make posts URLs look nicer. I am using nginx as web server. I am developing the site, so currently on an IP, not a domain. I am redirecting the current root domain <https://example.com/> to the main multisite path <https://example.com/en-us/> with Redirection plugin. This is my nginx conf file: ``` upstream php-handler-http { server 127.0.0.1:9000; #server unix:/var/run/php5-fpm.sock; } map $http_host $blogid { default 0; include /var/www/html/wp-content/uploads/nginx-helper/map.conf; } server { listen 80 default_server; server_name 123.123.123.123; root /var/www/html/; index index.php; access_log /var/log/nginx/wordpress_http_access.log combined; error_log /var/log/nginx/wordpress_http_error.log; # set max upload size client_max_body_size 2G; fastcgi_buffers 64 4K; if (!-e $request_filename) { rewrite /wp-admin$ $scheme://$host$request_uri/ permanent; rewrite ^(/[^/]+)?(/wp-.*) $2 last; rewrite ^(/[^/]+)?(/.*\.php) $2 last; } location / { try_files $uri $uri/ /index.php?$args ; } location ~ \.php(?:$|/) { fastcgi_split_path_info ^(.+\.php)(/.+)$; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_pass php-handler-http; fastcgi_read_timeout 600; } location = /favicon.ico { log_not_found off; access_log off; } location = /robots.txt { allow all; log_not_found off; access_log off; } location ~* \.(htaccess|htpasswd) { deny all; } # set long EXPIRES header on static assets location ~* \.(?:jpg|jpeg|gif|bmp|ico|png|css|js|swf)$ { expires 24h; access_log off; } } ```
I've run your code and it works fine to me except for the inclusion in file-access.php: `require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');` enable debug to see if there are errors depending on other issues and not regarding these specific code lines. But.. as per WP documentation: [actions reference](https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request) the earlier action hook where the authentication process is completed and cookies are set is `init` as suggested in [@Mohsin](https://wordpress.stackexchange.com/users/30852/mohsin) comment so I suggest to use this code in *file-access.php* ``` /* you probably don't need a theme */ define( 'WP_USE_THEMES', false ); /* defining a constant here allows you to exit functions when not needed */ define('FROM_EXTERNAL_FILE',true); /* unless you've renamed your wp-content folder this path will always point to wp-load.php even in subfolders installations */ require_once(explode("wp-content", __FILE__)[0] . "wp-load.php"); ``` and move the check in your file functions.php which gets loaded with the whole WP environment by *wp-load.php* ``` function is_logged_function(){ if ( !defined ('FROM_EXTERNAL_FILE') ) return; if ( is_user_logged_in()){ echo "logged"; echo get_current_user_id(); } else{ echo "not logged"; } } add_action('init', 'is_logged_function'); ```
358,827
<p>In an upcoming WordPress project I have to display a listing of offices, and these offices would have a bunch of user fillable fields. </p> <p>I have spent some time thinking about the anatomy of an office and decided it would have the following:</p> <p>Things that make up an office (in my scenario):</p> <ul> <li>Name</li> <li>Address line 1</li> <li>Address line 2</li> <li>City</li> <li>Street</li> <li>Postcode</li> <li>Is opening soon?</li> <li>Opening date?</li> <li>Latitude</li> <li>Longlitude</li> <li>Summary/ short description</li> <li>Price per day currency</li> <li>key points - access, parking, cafe, other assets</li> <li>Contact phone number</li> <li>Contact email</li> <li>Description of location/ centre</li> <li>Key features and benefits</li> <li>Photo of tour guide for office or centre</li> <li>Directions by tube/ train, bus, driving etc</li> <li>Reviews</li> <li>Photography</li> <li>Given name</li> <li>legal name</li> </ul> <p>I'm fairly new to WordPress but from the list I have given, would an office qualify as a custom post type, or is the leaning more towards a plugin or custom tables?</p> <p>I feel like things like <code>key features</code> would themselves be a taxonomy type much like the use of tags. For instance an office could have stuff like:</p> <ul> <li>Parking</li> <li>Wi-Fi</li> <li>Vending machine</li> </ul> <p>I'm just a bit hazy about what counts as what.</p>
[ { "answer_id": 358814, "author": "Mike", "author_id": 62621, "author_profile": "https://wordpress.stackexchange.com/users/62621", "pm_score": 0, "selected": false, "text": "<p>The file that would normally be called to kick off the Wordpress setup is wp-blog-header.php so maybe try swapping out <code>wp-load.php</code> for <code>wp-blog-header.php</code> in your code then re-test</p>\n" }, { "answer_id": 358913, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 3, "selected": true, "text": "<p>I've run your code and it works fine to me except for the inclusion in file-access.php:</p>\n\n<p><code>require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');</code> \nenable debug to see if there are errors depending on other issues and not regarding these specific code lines.</p>\n\n<p>But.. as per WP documentation: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request\" rel=\"nofollow noreferrer\">actions reference</a> the earlier action hook where the authentication process is completed and cookies are set is <code>init</code> as suggested in <a href=\"https://wordpress.stackexchange.com/users/30852/mohsin\">@Mohsin</a> comment so I suggest to use this code in <em>file-access.php</em></p>\n\n<pre><code>/* you probably don't need a theme */ \ndefine( 'WP_USE_THEMES', false ); \n\n/* defining a constant here allows you to exit functions when not needed */\ndefine('FROM_EXTERNAL_FILE',true);\n\n/* unless you've renamed your wp-content folder this path will always point to wp-load.php even in subfolders installations */\nrequire_once(explode(\"wp-content\", __FILE__)[0] . \"wp-load.php\");\n</code></pre>\n\n<p>and move the check in your file functions.php which gets loaded with the whole WP environment by <em>wp-load.php</em></p>\n\n<pre><code>function is_logged_function(){\n if ( !defined ('FROM_EXTERNAL_FILE') )\n return;\n if ( is_user_logged_in()){\n echo \"logged\";\n echo get_current_user_id();\n }\n else{\n echo \"not logged\";\n }\n}\nadd_action('init', 'is_logged_function');\n</code></pre>\n" } ]
2020/02/17
[ "https://wordpress.stackexchange.com/questions/358827", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146071/" ]
In an upcoming WordPress project I have to display a listing of offices, and these offices would have a bunch of user fillable fields. I have spent some time thinking about the anatomy of an office and decided it would have the following: Things that make up an office (in my scenario): * Name * Address line 1 * Address line 2 * City * Street * Postcode * Is opening soon? * Opening date? * Latitude * Longlitude * Summary/ short description * Price per day currency * key points - access, parking, cafe, other assets * Contact phone number * Contact email * Description of location/ centre * Key features and benefits * Photo of tour guide for office or centre * Directions by tube/ train, bus, driving etc * Reviews * Photography * Given name * legal name I'm fairly new to WordPress but from the list I have given, would an office qualify as a custom post type, or is the leaning more towards a plugin or custom tables? I feel like things like `key features` would themselves be a taxonomy type much like the use of tags. For instance an office could have stuff like: * Parking * Wi-Fi * Vending machine I'm just a bit hazy about what counts as what.
I've run your code and it works fine to me except for the inclusion in file-access.php: `require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');` enable debug to see if there are errors depending on other issues and not regarding these specific code lines. But.. as per WP documentation: [actions reference](https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request) the earlier action hook where the authentication process is completed and cookies are set is `init` as suggested in [@Mohsin](https://wordpress.stackexchange.com/users/30852/mohsin) comment so I suggest to use this code in *file-access.php* ``` /* you probably don't need a theme */ define( 'WP_USE_THEMES', false ); /* defining a constant here allows you to exit functions when not needed */ define('FROM_EXTERNAL_FILE',true); /* unless you've renamed your wp-content folder this path will always point to wp-load.php even in subfolders installations */ require_once(explode("wp-content", __FILE__)[0] . "wp-load.php"); ``` and move the check in your file functions.php which gets loaded with the whole WP environment by *wp-load.php* ``` function is_logged_function(){ if ( !defined ('FROM_EXTERNAL_FILE') ) return; if ( is_user_logged_in()){ echo "logged"; echo get_current_user_id(); } else{ echo "not logged"; } } add_action('init', 'is_logged_function'); ```
358,852
<p>I'm making a custom recent-posts shortcode and I have a problem with the thumbnail image, it always shows it above everything else (permalink, title, etc...) even though I put it after in the code, is there something in wordpress that forces this behavior ?</p> <p>Here is the code:</p> <pre><code>function mmx_recent_posts_shortcode($atts, $content = NULL) { $atts = shortcode_atts( [ 'orderby' =&gt; 'date', 'posts_per_page' =&gt; '3' ], $atts, 'recent-posts' ); $query = new WP_Query( $atts ); if ( $query-&gt;have_posts() ) { $output = '&lt;div class="row"&gt;'; while($query-&gt;have_posts()) : $query-&gt;the_post(); $output .= '&lt;div class="col span_4"&gt; &lt;h4&gt;' . get_the_title() . '&lt;/h4&gt; &lt;a href="' . get_permalink() . '"&gt;Lire la suite&lt;/a&gt;' . the_post_thumbnail('thumbnail', ['class' =&gt; 'droplet-img', 'title' =&gt; get_the_title()]) . ' &lt;/div&gt;'; endwhile; wp_reset_query(); return $output ; '&lt;/div&gt;'; } } add_shortcode('mmx-recent-posts', 'mmx_recent_posts_shortcode'); </code></pre> <p>The css code for <em>droplet-img</em>:</p> <pre><code>.droplet-img { border-radius: 0 50% 50%; } </code></pre> <p>and here is a screenshot of how it is right now:</p> <p><a href="https://i.stack.imgur.com/S4DSz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S4DSz.png" alt="how it looks"></a></p> <p>and here of how I want it to be:</p> <p><a href="https://i.stack.imgur.com/AzJBO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AzJBO.png" alt="enter image description here"></a></p> <p>If anybody has any idea how to fix it, I'd greatly appreciate it!</p> <p>Thanks!</p>
[ { "answer_id": 358862, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": false, "text": "<p>The problem is:</p>\n\n<p><code>the_post_thumbnail()</code> outputs its content immediately. It's basically like <code>echo</code>ing instead of <code>return</code>ing.</p>\n\n<p>To fix it, you should be able to just replace</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>the_post_thumbnail('thumbnail', ['class' =&gt; 'droplet-img', 'title' =&gt; get_the_title()])\n</code></pre>\n\n<p>with</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>get_the_post_thumbnail('thumbnail', ['class' =&gt; 'droplet-img', 'title' =&gt; get_the_title()])\n</code></pre>\n" }, { "answer_id": 358908, "author": "Alex Mattelon", "author_id": 182873, "author_profile": "https://wordpress.stackexchange.com/users/182873", "pm_score": 1, "selected": false, "text": "<p>Thanks everybody for your help, it helped me go in the correct direction.</p>\n\n<p>Here is my final code:</p>\n\n<pre><code>function mmx_recent_posts_shortcode()\n{\n $args = array(\n 'orderby' =&gt; 'date',\n 'posts_per_page' =&gt; 3\n );\n\n $posts = get_posts( array( $args ) );\n\n foreach ( $posts as $post ) {\n if ( has_post_thumbnail( $post-&gt;ID ) ) {\n echo '&lt;div class=\"col span_4 mmx-recent-posts\"&gt;\n &lt;h4&gt;' . esc_attr( $post-&gt;post_title ) . '&lt;/h4&gt;\n &lt;a href=\"' . get_permalink( $post-&gt;ID ) . '\"&gt;Lire la suite&lt;/a&gt;' . get_the_post_thumbnail($post-&gt;ID, 'thumbnail', array('class' =&gt; 'droplet-img', 'title' =&gt; esc_attr( $post-&gt;post_title ))) . '\n &lt;/div&gt;';\n }\n }\n}\n</code></pre>\n" } ]
2020/02/17
[ "https://wordpress.stackexchange.com/questions/358852", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/182873/" ]
I'm making a custom recent-posts shortcode and I have a problem with the thumbnail image, it always shows it above everything else (permalink, title, etc...) even though I put it after in the code, is there something in wordpress that forces this behavior ? Here is the code: ``` function mmx_recent_posts_shortcode($atts, $content = NULL) { $atts = shortcode_atts( [ 'orderby' => 'date', 'posts_per_page' => '3' ], $atts, 'recent-posts' ); $query = new WP_Query( $atts ); if ( $query->have_posts() ) { $output = '<div class="row">'; while($query->have_posts()) : $query->the_post(); $output .= '<div class="col span_4"> <h4>' . get_the_title() . '</h4> <a href="' . get_permalink() . '">Lire la suite</a>' . the_post_thumbnail('thumbnail', ['class' => 'droplet-img', 'title' => get_the_title()]) . ' </div>'; endwhile; wp_reset_query(); return $output ; '</div>'; } } add_shortcode('mmx-recent-posts', 'mmx_recent_posts_shortcode'); ``` The css code for *droplet-img*: ``` .droplet-img { border-radius: 0 50% 50%; } ``` and here is a screenshot of how it is right now: [![how it looks](https://i.stack.imgur.com/S4DSz.png)](https://i.stack.imgur.com/S4DSz.png) and here of how I want it to be: [![enter image description here](https://i.stack.imgur.com/AzJBO.png)](https://i.stack.imgur.com/AzJBO.png) If anybody has any idea how to fix it, I'd greatly appreciate it! Thanks!
The problem is: `the_post_thumbnail()` outputs its content immediately. It's basically like `echo`ing instead of `return`ing. To fix it, you should be able to just replace ```php the_post_thumbnail('thumbnail', ['class' => 'droplet-img', 'title' => get_the_title()]) ``` with ```php get_the_post_thumbnail('thumbnail', ['class' => 'droplet-img', 'title' => get_the_title()]) ```
358,855
<p>I have wordpress v5.3.2 installed on my site. I want to make it a MultiSite and I have read and done all steps mentioned in Wordpress documentation. I like to set my network as SubDomains. I have Direct Admin panel and I don't know if there is anything else I must do on my host.</p> <p>Everything seems fine since my Network setup is completed and I am able to create sites on my network. The problem is that I can not access either the subdomain address or its dashboard. I get an Internal Server Error when trying to go to dashboard.</p> <p>I wonder why it doesn't work or recognize the wordpress installation on any of my sub-domains. Here's what is written about MU on Wordpress site:</p> <p>"Multisite is a WordPress feature which allows users to create a network of sites on a <strong>single WordPress installation</strong>" <a href="https://www.wpbeginner.com/glossary/multisite/" rel="nofollow noreferrer">https://www.wpbeginner.com/glossary/multisite/</a></p> <p>I'd appreciate your help because I am stuck with it for days. </p> <p>My main site: <a href="http://zagraco.ir/" rel="nofollow noreferrer">http://zagraco.ir/</a></p> <p>Subdomain: elixir.zagraco.ir </p> <p>** Also, I need to create 10 subdomains. Is there any limitations for subdomains? </p>
[ { "answer_id": 358862, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": false, "text": "<p>The problem is:</p>\n\n<p><code>the_post_thumbnail()</code> outputs its content immediately. It's basically like <code>echo</code>ing instead of <code>return</code>ing.</p>\n\n<p>To fix it, you should be able to just replace</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>the_post_thumbnail('thumbnail', ['class' =&gt; 'droplet-img', 'title' =&gt; get_the_title()])\n</code></pre>\n\n<p>with</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>get_the_post_thumbnail('thumbnail', ['class' =&gt; 'droplet-img', 'title' =&gt; get_the_title()])\n</code></pre>\n" }, { "answer_id": 358908, "author": "Alex Mattelon", "author_id": 182873, "author_profile": "https://wordpress.stackexchange.com/users/182873", "pm_score": 1, "selected": false, "text": "<p>Thanks everybody for your help, it helped me go in the correct direction.</p>\n\n<p>Here is my final code:</p>\n\n<pre><code>function mmx_recent_posts_shortcode()\n{\n $args = array(\n 'orderby' =&gt; 'date',\n 'posts_per_page' =&gt; 3\n );\n\n $posts = get_posts( array( $args ) );\n\n foreach ( $posts as $post ) {\n if ( has_post_thumbnail( $post-&gt;ID ) ) {\n echo '&lt;div class=\"col span_4 mmx-recent-posts\"&gt;\n &lt;h4&gt;' . esc_attr( $post-&gt;post_title ) . '&lt;/h4&gt;\n &lt;a href=\"' . get_permalink( $post-&gt;ID ) . '\"&gt;Lire la suite&lt;/a&gt;' . get_the_post_thumbnail($post-&gt;ID, 'thumbnail', array('class' =&gt; 'droplet-img', 'title' =&gt; esc_attr( $post-&gt;post_title ))) . '\n &lt;/div&gt;';\n }\n }\n}\n</code></pre>\n" } ]
2020/02/17
[ "https://wordpress.stackexchange.com/questions/358855", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121268/" ]
I have wordpress v5.3.2 installed on my site. I want to make it a MultiSite and I have read and done all steps mentioned in Wordpress documentation. I like to set my network as SubDomains. I have Direct Admin panel and I don't know if there is anything else I must do on my host. Everything seems fine since my Network setup is completed and I am able to create sites on my network. The problem is that I can not access either the subdomain address or its dashboard. I get an Internal Server Error when trying to go to dashboard. I wonder why it doesn't work or recognize the wordpress installation on any of my sub-domains. Here's what is written about MU on Wordpress site: "Multisite is a WordPress feature which allows users to create a network of sites on a **single WordPress installation**" <https://www.wpbeginner.com/glossary/multisite/> I'd appreciate your help because I am stuck with it for days. My main site: <http://zagraco.ir/> Subdomain: elixir.zagraco.ir \*\* Also, I need to create 10 subdomains. Is there any limitations for subdomains?
The problem is: `the_post_thumbnail()` outputs its content immediately. It's basically like `echo`ing instead of `return`ing. To fix it, you should be able to just replace ```php the_post_thumbnail('thumbnail', ['class' => 'droplet-img', 'title' => get_the_title()]) ``` with ```php get_the_post_thumbnail('thumbnail', ['class' => 'droplet-img', 'title' => get_the_title()]) ```
358,870
<p>I have to make calls to multiple pages of a Woocommerce product database (getting all products in one go seems to not be an option), and the looping and collection of the results isn't working as I expect. I should see an array with just under 900 objects, but all I'm seeing is an empty array. I'm very new to PHP. THe relevant code below:</p> <pre><code>function get_awesome_products() { for ($count = 1; $count &lt;= 9; $count++ ) { if ($count &lt; 2) { $completeProductList = []; } $baseRequest = 'https://myawesomeapi/wp-json/wc/v3/products/? consumer_key=xxxx&amp;consumer_secret=xxxx&amp;per_page=100&amp;page='; $request = wp_remote_get( $baseRequest . (string)$count); $body = wp_remote_retrieve_body( $request ); $data = array_values(json_decode( $body, true )); if (count($completeProductList &lt; 1)) { $completeProductList = $data; } else { $completeProductList = array_merge($completeProductList, $data); } } return new WP_REST_Response($completeProductList, 200); } add_action('rest_api_init', function() { register_rest_route('awe/v1', 'aweproducts', array( 'methods' =&gt; 'GET', 'callback' =&gt; 'get_awesome_products', 'permission_callback' =&gt; function () { return true; } )); }); </code></pre>
[ { "answer_id": 358862, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": false, "text": "<p>The problem is:</p>\n\n<p><code>the_post_thumbnail()</code> outputs its content immediately. It's basically like <code>echo</code>ing instead of <code>return</code>ing.</p>\n\n<p>To fix it, you should be able to just replace</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>the_post_thumbnail('thumbnail', ['class' =&gt; 'droplet-img', 'title' =&gt; get_the_title()])\n</code></pre>\n\n<p>with</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>get_the_post_thumbnail('thumbnail', ['class' =&gt; 'droplet-img', 'title' =&gt; get_the_title()])\n</code></pre>\n" }, { "answer_id": 358908, "author": "Alex Mattelon", "author_id": 182873, "author_profile": "https://wordpress.stackexchange.com/users/182873", "pm_score": 1, "selected": false, "text": "<p>Thanks everybody for your help, it helped me go in the correct direction.</p>\n\n<p>Here is my final code:</p>\n\n<pre><code>function mmx_recent_posts_shortcode()\n{\n $args = array(\n 'orderby' =&gt; 'date',\n 'posts_per_page' =&gt; 3\n );\n\n $posts = get_posts( array( $args ) );\n\n foreach ( $posts as $post ) {\n if ( has_post_thumbnail( $post-&gt;ID ) ) {\n echo '&lt;div class=\"col span_4 mmx-recent-posts\"&gt;\n &lt;h4&gt;' . esc_attr( $post-&gt;post_title ) . '&lt;/h4&gt;\n &lt;a href=\"' . get_permalink( $post-&gt;ID ) . '\"&gt;Lire la suite&lt;/a&gt;' . get_the_post_thumbnail($post-&gt;ID, 'thumbnail', array('class' =&gt; 'droplet-img', 'title' =&gt; esc_attr( $post-&gt;post_title ))) . '\n &lt;/div&gt;';\n }\n }\n}\n</code></pre>\n" } ]
2020/02/17
[ "https://wordpress.stackexchange.com/questions/358870", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/181194/" ]
I have to make calls to multiple pages of a Woocommerce product database (getting all products in one go seems to not be an option), and the looping and collection of the results isn't working as I expect. I should see an array with just under 900 objects, but all I'm seeing is an empty array. I'm very new to PHP. THe relevant code below: ``` function get_awesome_products() { for ($count = 1; $count <= 9; $count++ ) { if ($count < 2) { $completeProductList = []; } $baseRequest = 'https://myawesomeapi/wp-json/wc/v3/products/? consumer_key=xxxx&consumer_secret=xxxx&per_page=100&page='; $request = wp_remote_get( $baseRequest . (string)$count); $body = wp_remote_retrieve_body( $request ); $data = array_values(json_decode( $body, true )); if (count($completeProductList < 1)) { $completeProductList = $data; } else { $completeProductList = array_merge($completeProductList, $data); } } return new WP_REST_Response($completeProductList, 200); } add_action('rest_api_init', function() { register_rest_route('awe/v1', 'aweproducts', array( 'methods' => 'GET', 'callback' => 'get_awesome_products', 'permission_callback' => function () { return true; } )); }); ```
The problem is: `the_post_thumbnail()` outputs its content immediately. It's basically like `echo`ing instead of `return`ing. To fix it, you should be able to just replace ```php the_post_thumbnail('thumbnail', ['class' => 'droplet-img', 'title' => get_the_title()]) ``` with ```php get_the_post_thumbnail('thumbnail', ['class' => 'droplet-img', 'title' => get_the_title()]) ```
358,886
<p>I changed my WordPress language to Arabic, Now <code>get_the_date()</code> returns <code>يناير 30, 2020</code> (half Arabic &amp; half english) but I need to get date full Arabic like: <code>يناير ٣٠, ٢٠٢٠</code> </p> <p>How can I do this?</p>
[ { "answer_id": 358862, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": false, "text": "<p>The problem is:</p>\n\n<p><code>the_post_thumbnail()</code> outputs its content immediately. It's basically like <code>echo</code>ing instead of <code>return</code>ing.</p>\n\n<p>To fix it, you should be able to just replace</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>the_post_thumbnail('thumbnail', ['class' =&gt; 'droplet-img', 'title' =&gt; get_the_title()])\n</code></pre>\n\n<p>with</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>get_the_post_thumbnail('thumbnail', ['class' =&gt; 'droplet-img', 'title' =&gt; get_the_title()])\n</code></pre>\n" }, { "answer_id": 358908, "author": "Alex Mattelon", "author_id": 182873, "author_profile": "https://wordpress.stackexchange.com/users/182873", "pm_score": 1, "selected": false, "text": "<p>Thanks everybody for your help, it helped me go in the correct direction.</p>\n\n<p>Here is my final code:</p>\n\n<pre><code>function mmx_recent_posts_shortcode()\n{\n $args = array(\n 'orderby' =&gt; 'date',\n 'posts_per_page' =&gt; 3\n );\n\n $posts = get_posts( array( $args ) );\n\n foreach ( $posts as $post ) {\n if ( has_post_thumbnail( $post-&gt;ID ) ) {\n echo '&lt;div class=\"col span_4 mmx-recent-posts\"&gt;\n &lt;h4&gt;' . esc_attr( $post-&gt;post_title ) . '&lt;/h4&gt;\n &lt;a href=\"' . get_permalink( $post-&gt;ID ) . '\"&gt;Lire la suite&lt;/a&gt;' . get_the_post_thumbnail($post-&gt;ID, 'thumbnail', array('class' =&gt; 'droplet-img', 'title' =&gt; esc_attr( $post-&gt;post_title ))) . '\n &lt;/div&gt;';\n }\n }\n}\n</code></pre>\n" } ]
2020/02/18
[ "https://wordpress.stackexchange.com/questions/358886", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136708/" ]
I changed my WordPress language to Arabic, Now `get_the_date()` returns `يناير 30, 2020` (half Arabic & half english) but I need to get date full Arabic like: `يناير ٣٠, ٢٠٢٠` How can I do this?
The problem is: `the_post_thumbnail()` outputs its content immediately. It's basically like `echo`ing instead of `return`ing. To fix it, you should be able to just replace ```php the_post_thumbnail('thumbnail', ['class' => 'droplet-img', 'title' => get_the_title()]) ``` with ```php get_the_post_thumbnail('thumbnail', ['class' => 'droplet-img', 'title' => get_the_title()]) ```
358,925
<p>In WordPress, how do I get the number of posts next to <code>&lt;?php single_cat_title(''); ?&gt;</code> in the category.php file?</p> <pre><code>&lt;h1&gt;&lt;?php single_cat_title(''); ?&gt; (&lt;?php ????code to count number of posts in the category shown?&gt;?? ?&gt;)&lt;/h1&gt; </code></pre>
[ { "answer_id": 358926, "author": "Dipendra Pancholi", "author_id": 182923, "author_profile": "https://wordpress.stackexchange.com/users/182923", "pm_score": 0, "selected": false, "text": "<p>You can use the function get_category() to get the category object and then just simply echo the $count property value.</p>\n\n<pre><code>$cat_count = get_category( 'ID OR ROW OBJECT' );\necho $cat_count-&gt;count;\n</code></pre>\n\n<p>If you also want to get the category object or ID before that then use this code:</p>\n\n<pre><code>$categories = get_the_category();\n$category_id = $categories[0]-&gt;cat_ID;\n</code></pre>\n" }, { "answer_id": 358934, "author": "Glen Charles Rowell", "author_id": 170708, "author_profile": "https://wordpress.stackexchange.com/users/170708", "pm_score": 1, "selected": false, "text": "<p>I figured out how to do it. </p>\n\n<p>This code shows the number of posts on a page after clicking on a category in WordPress. Even if the post has lots of categories.</p>\n\n<pre><code>&lt;?php $category = get_queried_object(); echo $category-&gt;count; ?&gt;\n</code></pre>\n\n<p>I used this code as the code was in the category.php file and not part of the regular loop.</p>\n\n<p>I hope this code helps anyone else if they are having the same type of problem.</p>\n" } ]
2020/02/18
[ "https://wordpress.stackexchange.com/questions/358925", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/170708/" ]
In WordPress, how do I get the number of posts next to `<?php single_cat_title(''); ?>` in the category.php file? ``` <h1><?php single_cat_title(''); ?> (<?php ????code to count number of posts in the category shown?>?? ?>)</h1> ```
I figured out how to do it. This code shows the number of posts on a page after clicking on a category in WordPress. Even if the post has lots of categories. ``` <?php $category = get_queried_object(); echo $category->count; ?> ``` I used this code as the code was in the category.php file and not part of the regular loop. I hope this code helps anyone else if they are having the same type of problem.
358,953
<p>I have a simple shortcode which parses "user" id from URL and loads specific data from another mysql db for that user inside one custom page:</p> <pre><code>$sql_u = 'user'; $sql_p = 'password'; $sql_db = 'database'; $sql_ip = '10.10.10.10'; function fetch_data_func ($atts) { global $wpdb,$sql_u,$sql_p,$sql_db,$sql_ip; $reg = new wpdb($sql_u,$sql_p,$sql_db,$sql_ip); $user = get_query_var('user'); $result = $reg-&gt;get_row($wpdb-&gt;prepare("SELECT * from data_table WHERE url_id=%s",$user)); return $result-&gt;{$atts['text']}; } add_shortcode('fetch_data', 'fetch_data_func'); </code></pre> <p>And this is how I call this shortcode:</p> <pre><code>Name: [fetch_data text="name"] Some random text or other WP blocks Address: [fetch_data text="address"] Some random text or other WP blocks City: [fetch_data text="city"] etc. </code></pre> <p>I have about 20 columns in that specific mysql db for each user which means about 20 shortcode calls on various parts of the same page in wordpress.</p> <p>For obvious reasons, when calling the shortcode multiple times inside one single page, loading times drastically increase. I believe with each shortcode call, a new query to database is performed. So, when calling the shortcode 20 times, then 20 queries are made, always fetching the same data and this means (in my case) about 10 secs of page loading on pretty decent apache server.</p> <p>My question is, how would it be even possible to modify the shortcode so it will actually perform the query only once and fetch all data needed inside "get_row" function and then just use this shortcode inside one single page multiple times without performing any additional new queries each time. Is this even doable in that kind of form or should I look for another approach? I also tested this with get_var and multiple shortcodes, but the result is the same, slow. I'm actually lost here.</p> <p>Or maybe even better question, would it be possible to call this shortcode multiple times from various parts of the same page without performing a sql query each time again?</p> <p>Thank you in advance so much for any kind of help!</p>
[ { "answer_id": 358958, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 3, "selected": true, "text": "<p>PHP and many other languages have a special construct to combine state an behavior – because that's what you want. That construct is called an <strong>object</strong>.</p>\n\n<p>Objects are defined by <strong>classes</strong>. So you need a class that remembers the current user data (the state) and delivers the parts that you need (the behavior). This can be very simple. Create a new PHP file named <code>UserData.php</code> and include it right before you register the shortcode.</p>\n\n<p>The content of the file should look similar to this:</p>\n\n<pre><code>namespace WPSE;\n\nclass UserData\n{\n private $user, $sql_u, $sql_p, $sql_db, $sql_ip;\n\n public function __construct( $sql_u, $sql_p, $sql_db, $sql_ip )\n {\n $this-&gt;sql_u = $sql_u;\n $this-&gt;sql_u = $sql_p;\n $this-&gt;sql_u = $sql_db;\n $this-&gt;sql_u = $sql_ip;\n }\n\n public function fetch( $atts )\n {\n if ( empty ( $this-&gt;user ) {\n $this-&gt;fetch_user();\n }\n return $this-&gt;user-&gt;{$atts['text']};\n }\n\n private function fetch_user()\n {\n $reg = new \\wpdb( \n $this-&gt;sql_u, \n $this-&gt;sql_p, \n $this-&gt;sql_db, \n $this-&gt;sql_ip\n );\n $user_id = get_query_var('user');\n $this-&gt;user = $reg-&gt;get_row(\n $reg-&gt;prepare(\n \"SELECT * from data_table WHERE url_id=%s\",\n $user_id\n )\n );\n }\n}\n</code></pre>\n\n<p>And then you register the shortcode with the namespace:</p>\n\n<pre><code>include_once ('UserData.php');\n$user_data = new \\WPSE\\UserData( $sql_u, $sql_p, $sql_db, $sql_ip );\nadd_shortcode( 'fetch_data', [ $user_data, 'fetch' ] );\n</code></pre>\n\n<p>Note that this is completely untested. I just want to give you an idea on how to handle cases like this one.</p>\n\n<p>Also, welcome to WordPress Stack Exchange! :)</p>\n" }, { "answer_id": 358967, "author": "hamdirizal", "author_id": 133145, "author_profile": "https://wordpress.stackexchange.com/users/133145", "pm_score": 0, "selected": false, "text": "<p>You can use commas to separate the parameters and display the data once. This way you can pick whichever fields you want to show.</p>\n\n<pre><code>[fetch_data fields=\"First Name:first_name,Last Name:last_name,City:city\"]\n</code></pre>\n\n<p>This is the shortcode function:</p>\n\n<pre><code>add_shortcode('fetch_data', 'fetch_data_func');\n\nfunction fetch_data_func($attr){\n $user_arr = get_user_data_from_db();//use your own code\n\n //Split by comma then by colon\n $fields = explode(',', $attr['fields']);\n $fields = array_map(function($item){\n $field = explode(':', $item);\n return array( 'label'=&gt;$field[0],'name'=&gt;$field[1] );\n }, $fields);\n\n //Use Output Buffering so you can include template here\n ob_start();\n foreach ($fields as $field) {\n echo $field['label'] . ': ' . $user_arr[$field['name']] . '&lt;br&gt;';\n //Will show like this \n //First name: John\n //City: New York\n }\n return ob_get_clean();\n}\n</code></pre>\n" } ]
2020/02/18
[ "https://wordpress.stackexchange.com/questions/358953", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/182948/" ]
I have a simple shortcode which parses "user" id from URL and loads specific data from another mysql db for that user inside one custom page: ``` $sql_u = 'user'; $sql_p = 'password'; $sql_db = 'database'; $sql_ip = '10.10.10.10'; function fetch_data_func ($atts) { global $wpdb,$sql_u,$sql_p,$sql_db,$sql_ip; $reg = new wpdb($sql_u,$sql_p,$sql_db,$sql_ip); $user = get_query_var('user'); $result = $reg->get_row($wpdb->prepare("SELECT * from data_table WHERE url_id=%s",$user)); return $result->{$atts['text']}; } add_shortcode('fetch_data', 'fetch_data_func'); ``` And this is how I call this shortcode: ``` Name: [fetch_data text="name"] Some random text or other WP blocks Address: [fetch_data text="address"] Some random text or other WP blocks City: [fetch_data text="city"] etc. ``` I have about 20 columns in that specific mysql db for each user which means about 20 shortcode calls on various parts of the same page in wordpress. For obvious reasons, when calling the shortcode multiple times inside one single page, loading times drastically increase. I believe with each shortcode call, a new query to database is performed. So, when calling the shortcode 20 times, then 20 queries are made, always fetching the same data and this means (in my case) about 10 secs of page loading on pretty decent apache server. My question is, how would it be even possible to modify the shortcode so it will actually perform the query only once and fetch all data needed inside "get\_row" function and then just use this shortcode inside one single page multiple times without performing any additional new queries each time. Is this even doable in that kind of form or should I look for another approach? I also tested this with get\_var and multiple shortcodes, but the result is the same, slow. I'm actually lost here. Or maybe even better question, would it be possible to call this shortcode multiple times from various parts of the same page without performing a sql query each time again? Thank you in advance so much for any kind of help!
PHP and many other languages have a special construct to combine state an behavior – because that's what you want. That construct is called an **object**. Objects are defined by **classes**. So you need a class that remembers the current user data (the state) and delivers the parts that you need (the behavior). This can be very simple. Create a new PHP file named `UserData.php` and include it right before you register the shortcode. The content of the file should look similar to this: ``` namespace WPSE; class UserData { private $user, $sql_u, $sql_p, $sql_db, $sql_ip; public function __construct( $sql_u, $sql_p, $sql_db, $sql_ip ) { $this->sql_u = $sql_u; $this->sql_u = $sql_p; $this->sql_u = $sql_db; $this->sql_u = $sql_ip; } public function fetch( $atts ) { if ( empty ( $this->user ) { $this->fetch_user(); } return $this->user->{$atts['text']}; } private function fetch_user() { $reg = new \wpdb( $this->sql_u, $this->sql_p, $this->sql_db, $this->sql_ip ); $user_id = get_query_var('user'); $this->user = $reg->get_row( $reg->prepare( "SELECT * from data_table WHERE url_id=%s", $user_id ) ); } } ``` And then you register the shortcode with the namespace: ``` include_once ('UserData.php'); $user_data = new \WPSE\UserData( $sql_u, $sql_p, $sql_db, $sql_ip ); add_shortcode( 'fetch_data', [ $user_data, 'fetch' ] ); ``` Note that this is completely untested. I just want to give you an idea on how to handle cases like this one. Also, welcome to WordPress Stack Exchange! :)
359,025
<p>I made a grid with bootstrap where i want to show 5 differents posts but for some reason it duplicates the grids and shows one post per grid. <a href="https://i.stack.imgur.com/2j0X5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2j0X5.png" alt="Here you can see how it starts to duplicate the grids"></a> <a href="https://i.stack.imgur.com/ORJfk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ORJfk.jpg" alt="This is how i would like it to work"></a></p> <p>First image shows how it starts to duplicate the grids 5 times instead of just showing 5 posts in those columns. Second picture shows how i would like to work.</p> <pre><code> &lt;?php get_header(); ?&gt; &lt;main&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;?php $args = array( &lt;?php 'post_type' =&gt;post_type' =&gt; 'post, 'posts_per_page' =&gt; 5, ); $blogposts = new WP_Query($args); while($blogposts-&gt;have_posts()) { $blogposts-&gt;the_post(); ?&gt; &lt;div class="col-md-6"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt; &lt;div class="card border-0"&gt; &lt;div class="card-picture"&gt; &lt;img class="card-img" src="&lt;?php echo get_the_post_thumbnail_url(get_the_ID()); ?&gt;" alt="Card image"&gt; &lt;div class="card-img-overlay d-flex flex-column"&gt; &lt;h5 class="card-title font-weight-bold"&gt;&lt;?php the_title(); ?&gt;&lt;/h5&gt; &lt;div class="mt-auto"&gt; Miika - &lt;i class="fas fa-clock"&gt;&lt;/i&gt; 16.2.2020 - Oppaat&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-6"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;div class="card border-0"&gt; &lt;div class="card-picture"&gt; &lt;img class="card-img" src="&lt;?php echo get_the_post_thumbnail_url(get_the_ID()); ?&gt;" alt="Card image"&gt; &lt;div class="card-img-overlay d-flex flex-column"&gt; &lt;h5 class="card-title font-weight-bold"&gt;&lt;?php the_title(); ?&gt;&lt;/h5&gt; &lt;div class="mt-auto"&gt;Miika - &lt;i class="fas fa-clock"&gt;&lt;/i&gt; 16.2.2020 - Oppaat&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-md-4"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;div class="card border-0"&gt; &lt;div class="card-pic"&gt; &lt;img class="card-img" src="&lt;?php echo get_the_post_thumbnail_url(get_the_ID()); ?&gt;" alt="Card image"&gt; &lt;div class="card-img-overlay d-flex flex-column"&gt; &lt;h3 class="card-title font-weight-bold"&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt; &lt;div class="mt-auto"&gt;Miika - &lt;i class="fas fa-clock"&gt;&lt;/i&gt; 16.2.2020 - Oppaat&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;div class="card border-0"&gt; &lt;div class="card-pic"&gt; &lt;img class="card-img" src="&lt;?php echo get_the_post_thumbnail_url(get_the_ID()); ?&gt;" alt="Card image"&gt; &lt;div class="card-img-overlay d-flex flex-column"&gt; &lt;h5 class="card-title font-weight-bold"&gt;&lt;?php the_title(); ?&gt;&lt;/h5&gt; &lt;div class="mt-auto"&gt;Miika - &lt;i class="fas fa-clock"&gt;&lt;/i&gt; 16.2.2020 - Oppaat&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;div class="card border-0"&gt; &lt;div class="card-pic"&gt; &lt;img class="card-img" src="&lt;?php echo get_the_post_thumbnail_url(get_the_ID()); ?&gt;" alt="Card image"&gt; &lt;div class="card-img-overlay d-flex flex-column"&gt; &lt;h5 class="card-title font-weight-bold"&gt;&lt;?php the_title(); ?&gt;&lt;/h5&gt; &lt;div class="mt-auto"&gt;Miika - &lt;i class="fas fa-clock"&gt;&lt;/i&gt; 16.2.2020 - Oppaat&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;?php } wp_reset_query(); </code></pre>
[ { "answer_id": 358958, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 3, "selected": true, "text": "<p>PHP and many other languages have a special construct to combine state an behavior – because that's what you want. That construct is called an <strong>object</strong>.</p>\n\n<p>Objects are defined by <strong>classes</strong>. So you need a class that remembers the current user data (the state) and delivers the parts that you need (the behavior). This can be very simple. Create a new PHP file named <code>UserData.php</code> and include it right before you register the shortcode.</p>\n\n<p>The content of the file should look similar to this:</p>\n\n<pre><code>namespace WPSE;\n\nclass UserData\n{\n private $user, $sql_u, $sql_p, $sql_db, $sql_ip;\n\n public function __construct( $sql_u, $sql_p, $sql_db, $sql_ip )\n {\n $this-&gt;sql_u = $sql_u;\n $this-&gt;sql_u = $sql_p;\n $this-&gt;sql_u = $sql_db;\n $this-&gt;sql_u = $sql_ip;\n }\n\n public function fetch( $atts )\n {\n if ( empty ( $this-&gt;user ) {\n $this-&gt;fetch_user();\n }\n return $this-&gt;user-&gt;{$atts['text']};\n }\n\n private function fetch_user()\n {\n $reg = new \\wpdb( \n $this-&gt;sql_u, \n $this-&gt;sql_p, \n $this-&gt;sql_db, \n $this-&gt;sql_ip\n );\n $user_id = get_query_var('user');\n $this-&gt;user = $reg-&gt;get_row(\n $reg-&gt;prepare(\n \"SELECT * from data_table WHERE url_id=%s\",\n $user_id\n )\n );\n }\n}\n</code></pre>\n\n<p>And then you register the shortcode with the namespace:</p>\n\n<pre><code>include_once ('UserData.php');\n$user_data = new \\WPSE\\UserData( $sql_u, $sql_p, $sql_db, $sql_ip );\nadd_shortcode( 'fetch_data', [ $user_data, 'fetch' ] );\n</code></pre>\n\n<p>Note that this is completely untested. I just want to give you an idea on how to handle cases like this one.</p>\n\n<p>Also, welcome to WordPress Stack Exchange! :)</p>\n" }, { "answer_id": 358967, "author": "hamdirizal", "author_id": 133145, "author_profile": "https://wordpress.stackexchange.com/users/133145", "pm_score": 0, "selected": false, "text": "<p>You can use commas to separate the parameters and display the data once. This way you can pick whichever fields you want to show.</p>\n\n<pre><code>[fetch_data fields=\"First Name:first_name,Last Name:last_name,City:city\"]\n</code></pre>\n\n<p>This is the shortcode function:</p>\n\n<pre><code>add_shortcode('fetch_data', 'fetch_data_func');\n\nfunction fetch_data_func($attr){\n $user_arr = get_user_data_from_db();//use your own code\n\n //Split by comma then by colon\n $fields = explode(',', $attr['fields']);\n $fields = array_map(function($item){\n $field = explode(':', $item);\n return array( 'label'=&gt;$field[0],'name'=&gt;$field[1] );\n }, $fields);\n\n //Use Output Buffering so you can include template here\n ob_start();\n foreach ($fields as $field) {\n echo $field['label'] . ': ' . $user_arr[$field['name']] . '&lt;br&gt;';\n //Will show like this \n //First name: John\n //City: New York\n }\n return ob_get_clean();\n}\n</code></pre>\n" } ]
2020/02/19
[ "https://wordpress.stackexchange.com/questions/359025", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/182997/" ]
I made a grid with bootstrap where i want to show 5 differents posts but for some reason it duplicates the grids and shows one post per grid. [![Here you can see how it starts to duplicate the grids](https://i.stack.imgur.com/2j0X5.png)](https://i.stack.imgur.com/2j0X5.png) [![This is how i would like it to work](https://i.stack.imgur.com/ORJfk.jpg)](https://i.stack.imgur.com/ORJfk.jpg) First image shows how it starts to duplicate the grids 5 times instead of just showing 5 posts in those columns. Second picture shows how i would like to work. ``` <?php get_header(); ?> <main> <div class="container"> <div class="row"> <?php $args = array( <?php 'post_type' =>post_type' => 'post, 'posts_per_page' => 5, ); $blogposts = new WP_Query($args); while($blogposts->have_posts()) { $blogposts->the_post(); ?> <div class="col-md-6"> <a href="<?php the_permalink(); ?> <div class="card border-0"> <div class="card-picture"> <img class="card-img" src="<?php echo get_the_post_thumbnail_url(get_the_ID()); ?>" alt="Card image"> <div class="card-img-overlay d-flex flex-column"> <h5 class="card-title font-weight-bold"><?php the_title(); ?></h5> <div class="mt-auto"> Miika - <i class="fas fa-clock"></i> 16.2.2020 - Oppaat</div> </div> </div> </div> </a> </div> <div class="col-md-6"> <a href="<?php the_permalink(); ?>"> <div class="card border-0"> <div class="card-picture"> <img class="card-img" src="<?php echo get_the_post_thumbnail_url(get_the_ID()); ?>" alt="Card image"> <div class="card-img-overlay d-flex flex-column"> <h5 class="card-title font-weight-bold"><?php the_title(); ?></h5> <div class="mt-auto">Miika - <i class="fas fa-clock"></i> 16.2.2020 - Oppaat</div> </div> </div> </div> </a> </div> </div> <div class="row"> <div class="col-md-4"> <a href="<?php the_permalink(); ?>"> <div class="card border-0"> <div class="card-pic"> <img class="card-img" src="<?php echo get_the_post_thumbnail_url(get_the_ID()); ?>" alt="Card image"> <div class="card-img-overlay d-flex flex-column"> <h3 class="card-title font-weight-bold"><?php the_title(); ?></h3> <div class="mt-auto">Miika - <i class="fas fa-clock"></i> 16.2.2020 - Oppaat</div> </div> </div> </div> </a> </div> <div class="col-md-4"> <a href="<?php the_permalink(); ?>"> <div class="card border-0"> <div class="card-pic"> <img class="card-img" src="<?php echo get_the_post_thumbnail_url(get_the_ID()); ?>" alt="Card image"> <div class="card-img-overlay d-flex flex-column"> <h5 class="card-title font-weight-bold"><?php the_title(); ?></h5> <div class="mt-auto">Miika - <i class="fas fa-clock"></i> 16.2.2020 - Oppaat</div> </div> </div> </div> </a> </div> <div class="col-md-4"> <a href="<?php the_permalink(); ?>"> <div class="card border-0"> <div class="card-pic"> <img class="card-img" src="<?php echo get_the_post_thumbnail_url(get_the_ID()); ?>" alt="Card image"> <div class="card-img-overlay d-flex flex-column"> <h5 class="card-title font-weight-bold"><?php the_title(); ?></h5> <div class="mt-auto">Miika - <i class="fas fa-clock"></i> 16.2.2020 - Oppaat</div> </div> </div> </div> </a> </div> <?php } wp_reset_query(); ```
PHP and many other languages have a special construct to combine state an behavior – because that's what you want. That construct is called an **object**. Objects are defined by **classes**. So you need a class that remembers the current user data (the state) and delivers the parts that you need (the behavior). This can be very simple. Create a new PHP file named `UserData.php` and include it right before you register the shortcode. The content of the file should look similar to this: ``` namespace WPSE; class UserData { private $user, $sql_u, $sql_p, $sql_db, $sql_ip; public function __construct( $sql_u, $sql_p, $sql_db, $sql_ip ) { $this->sql_u = $sql_u; $this->sql_u = $sql_p; $this->sql_u = $sql_db; $this->sql_u = $sql_ip; } public function fetch( $atts ) { if ( empty ( $this->user ) { $this->fetch_user(); } return $this->user->{$atts['text']}; } private function fetch_user() { $reg = new \wpdb( $this->sql_u, $this->sql_p, $this->sql_db, $this->sql_ip ); $user_id = get_query_var('user'); $this->user = $reg->get_row( $reg->prepare( "SELECT * from data_table WHERE url_id=%s", $user_id ) ); } } ``` And then you register the shortcode with the namespace: ``` include_once ('UserData.php'); $user_data = new \WPSE\UserData( $sql_u, $sql_p, $sql_db, $sql_ip ); add_shortcode( 'fetch_data', [ $user_data, 'fetch' ] ); ``` Note that this is completely untested. I just want to give you an idea on how to handle cases like this one. Also, welcome to WordPress Stack Exchange! :)
359,056
<p>I need to implement vuejs to load the categories of my store. I've read that the woocoomerce rest api need authenticate requets to work, so I'm trying to get the categories using oauth on localhost with https enabled:</p> <pre><code>// This is in my functions file to pass the parameters // wp_localize_script( 'main', 'woo', // array( // 'ajaxurl' =&gt; 'wp-ajax.php', // 'timestamp' =&gt; time(), // 'hash' =&gt; hash_hmac(), // 'nonce' // ) // ); </code></pre> <p>AJAX</p> <pre><code>// This is the JS part //$.ajax({ //method: 'GET', //url: 'wp-json/wc/v3/products/categories&amp;oauth_consumer_key="+woo.consumer_key+"&amp;oauth_signature_method="HMAC-SHA1&amp;oauth_timestamp="+woo.timestamp+"&amp;oauth_nonce="+woo.nonce+"&amp;oauth_signature=+woo.hash', // beforeSend: function (xhr) { // xhr.setRequestHeader ("Authorization", "OAuth " + btoa(username + ":" + password)); // }, </code></pre> <p>I get always a 401 response code, I'm not able to authenticate using ajax. I want to use the wp_localize_script to pass the needed timestamp and auth, but I'm not able to find how to do it correctly. Any example will be appreciated.</p> <p>UPDATE:</p> <p>I rewrite the che code using sally suggestion but I still get the 401 error response code. Here is the updated code</p> <p>PHP</p> <pre><code>wp_register_script('main', get_template_directory_uri().'/assets/js/main.js', array('jquery'), null ); $localize = array( 'ajaxurl' =&gt; admin_url('admin-ajax.php'), // Securing your WordPress plugin AJAX calls using nonces 'auth' =&gt; base64_encode('ck_32a46b36d90680e574e9de6456746a11cf07945:cs_0a6bd199a45c0b96e848a1401a14b18444fa46d8'), ); wp_localize_script('main', 'wp', $localize); wp_enqueue_script('main'); </code></pre> <p>JS </p> <pre><code> const app = new Vue({ el: '#app', data: {}, created: function(){ $.ajax({ method: 'GET', url: 'wp-json/wc/v3/products/categories', headers: { 'Authorization': "Basic "+ wp.auth }, success: function(response){ console.log(response); } }); }, destroyed: {}, mounted: {}, }); </code></pre> <p>I'm on localhost with a self signed cert to have the https, maybe this can be the problem? </p>
[ { "answer_id": 358958, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 3, "selected": true, "text": "<p>PHP and many other languages have a special construct to combine state an behavior – because that's what you want. That construct is called an <strong>object</strong>.</p>\n\n<p>Objects are defined by <strong>classes</strong>. So you need a class that remembers the current user data (the state) and delivers the parts that you need (the behavior). This can be very simple. Create a new PHP file named <code>UserData.php</code> and include it right before you register the shortcode.</p>\n\n<p>The content of the file should look similar to this:</p>\n\n<pre><code>namespace WPSE;\n\nclass UserData\n{\n private $user, $sql_u, $sql_p, $sql_db, $sql_ip;\n\n public function __construct( $sql_u, $sql_p, $sql_db, $sql_ip )\n {\n $this-&gt;sql_u = $sql_u;\n $this-&gt;sql_u = $sql_p;\n $this-&gt;sql_u = $sql_db;\n $this-&gt;sql_u = $sql_ip;\n }\n\n public function fetch( $atts )\n {\n if ( empty ( $this-&gt;user ) {\n $this-&gt;fetch_user();\n }\n return $this-&gt;user-&gt;{$atts['text']};\n }\n\n private function fetch_user()\n {\n $reg = new \\wpdb( \n $this-&gt;sql_u, \n $this-&gt;sql_p, \n $this-&gt;sql_db, \n $this-&gt;sql_ip\n );\n $user_id = get_query_var('user');\n $this-&gt;user = $reg-&gt;get_row(\n $reg-&gt;prepare(\n \"SELECT * from data_table WHERE url_id=%s\",\n $user_id\n )\n );\n }\n}\n</code></pre>\n\n<p>And then you register the shortcode with the namespace:</p>\n\n<pre><code>include_once ('UserData.php');\n$user_data = new \\WPSE\\UserData( $sql_u, $sql_p, $sql_db, $sql_ip );\nadd_shortcode( 'fetch_data', [ $user_data, 'fetch' ] );\n</code></pre>\n\n<p>Note that this is completely untested. I just want to give you an idea on how to handle cases like this one.</p>\n\n<p>Also, welcome to WordPress Stack Exchange! :)</p>\n" }, { "answer_id": 358967, "author": "hamdirizal", "author_id": 133145, "author_profile": "https://wordpress.stackexchange.com/users/133145", "pm_score": 0, "selected": false, "text": "<p>You can use commas to separate the parameters and display the data once. This way you can pick whichever fields you want to show.</p>\n\n<pre><code>[fetch_data fields=\"First Name:first_name,Last Name:last_name,City:city\"]\n</code></pre>\n\n<p>This is the shortcode function:</p>\n\n<pre><code>add_shortcode('fetch_data', 'fetch_data_func');\n\nfunction fetch_data_func($attr){\n $user_arr = get_user_data_from_db();//use your own code\n\n //Split by comma then by colon\n $fields = explode(',', $attr['fields']);\n $fields = array_map(function($item){\n $field = explode(':', $item);\n return array( 'label'=&gt;$field[0],'name'=&gt;$field[1] );\n }, $fields);\n\n //Use Output Buffering so you can include template here\n ob_start();\n foreach ($fields as $field) {\n echo $field['label'] . ': ' . $user_arr[$field['name']] . '&lt;br&gt;';\n //Will show like this \n //First name: John\n //City: New York\n }\n return ob_get_clean();\n}\n</code></pre>\n" } ]
2020/02/20
[ "https://wordpress.stackexchange.com/questions/359056", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/177581/" ]
I need to implement vuejs to load the categories of my store. I've read that the woocoomerce rest api need authenticate requets to work, so I'm trying to get the categories using oauth on localhost with https enabled: ``` // This is in my functions file to pass the parameters // wp_localize_script( 'main', 'woo', // array( // 'ajaxurl' => 'wp-ajax.php', // 'timestamp' => time(), // 'hash' => hash_hmac(), // 'nonce' // ) // ); ``` AJAX ``` // This is the JS part //$.ajax({ //method: 'GET', //url: 'wp-json/wc/v3/products/categories&oauth_consumer_key="+woo.consumer_key+"&oauth_signature_method="HMAC-SHA1&oauth_timestamp="+woo.timestamp+"&oauth_nonce="+woo.nonce+"&oauth_signature=+woo.hash', // beforeSend: function (xhr) { // xhr.setRequestHeader ("Authorization", "OAuth " + btoa(username + ":" + password)); // }, ``` I get always a 401 response code, I'm not able to authenticate using ajax. I want to use the wp\_localize\_script to pass the needed timestamp and auth, but I'm not able to find how to do it correctly. Any example will be appreciated. UPDATE: I rewrite the che code using sally suggestion but I still get the 401 error response code. Here is the updated code PHP ``` wp_register_script('main', get_template_directory_uri().'/assets/js/main.js', array('jquery'), null ); $localize = array( 'ajaxurl' => admin_url('admin-ajax.php'), // Securing your WordPress plugin AJAX calls using nonces 'auth' => base64_encode('ck_32a46b36d90680e574e9de6456746a11cf07945:cs_0a6bd199a45c0b96e848a1401a14b18444fa46d8'), ); wp_localize_script('main', 'wp', $localize); wp_enqueue_script('main'); ``` JS ``` const app = new Vue({ el: '#app', data: {}, created: function(){ $.ajax({ method: 'GET', url: 'wp-json/wc/v3/products/categories', headers: { 'Authorization': "Basic "+ wp.auth }, success: function(response){ console.log(response); } }); }, destroyed: {}, mounted: {}, }); ``` I'm on localhost with a self signed cert to have the https, maybe this can be the problem?
PHP and many other languages have a special construct to combine state an behavior – because that's what you want. That construct is called an **object**. Objects are defined by **classes**. So you need a class that remembers the current user data (the state) and delivers the parts that you need (the behavior). This can be very simple. Create a new PHP file named `UserData.php` and include it right before you register the shortcode. The content of the file should look similar to this: ``` namespace WPSE; class UserData { private $user, $sql_u, $sql_p, $sql_db, $sql_ip; public function __construct( $sql_u, $sql_p, $sql_db, $sql_ip ) { $this->sql_u = $sql_u; $this->sql_u = $sql_p; $this->sql_u = $sql_db; $this->sql_u = $sql_ip; } public function fetch( $atts ) { if ( empty ( $this->user ) { $this->fetch_user(); } return $this->user->{$atts['text']}; } private function fetch_user() { $reg = new \wpdb( $this->sql_u, $this->sql_p, $this->sql_db, $this->sql_ip ); $user_id = get_query_var('user'); $this->user = $reg->get_row( $reg->prepare( "SELECT * from data_table WHERE url_id=%s", $user_id ) ); } } ``` And then you register the shortcode with the namespace: ``` include_once ('UserData.php'); $user_data = new \WPSE\UserData( $sql_u, $sql_p, $sql_db, $sql_ip ); add_shortcode( 'fetch_data', [ $user_data, 'fetch' ] ); ``` Note that this is completely untested. I just want to give you an idea on how to handle cases like this one. Also, welcome to WordPress Stack Exchange! :)
359,092
<p>I am new to the Gutenberg editor. Previously I used the Classic editor (plugin) when editing WordPress. The editor area "resized" according to the browser window. With the Gutenberg approach I get a very narrow area to edit in. When I use the HTML-block all I get is a 890px wide and 250px high area with scrollbars. I feel claustrophobic!</p> <p>Are there some way to get around this? </p> <p>Similar question but with no good answers: <a href="https://wordpress.stackexchange.com/questions/338757/why-is-the-new-gutenberg-editor-so-narrow-and-how-to-make-it-wider">Why is the new Gutenberg editor so narrow, and how to make it wider?</a></p>
[ { "answer_id": 359105, "author": "Juan Díaz-Bustamante", "author_id": 183053, "author_profile": "https://wordpress.stackexchange.com/users/183053", "pm_score": 2, "selected": false, "text": "<p>You have to enqueue first the style editor css</p>\n\n<pre><code>function legit_block_editor_styles() {\nwp_enqueue_style( 'legit-editor-styles', get_theme_file_uri( '/style-editor.css' ), false, '2.3', 'all' );} \nadd_action( 'enqueue_block_editor_assets', 'legit_block_editor_styles' );\n</code></pre>\n\n<p>Then you have to create that style-editor.css file inside your theme and then add this inside that file:</p>\n\n<pre><code>.wp-block {\nmax-width: 100%;}\n</code></pre>\n" }, { "answer_id": 359532, "author": "Fredag", "author_id": 3977, "author_profile": "https://wordpress.stackexchange.com/users/3977", "pm_score": 1, "selected": true, "text": "<p>Here is what I did:</p>\n\n<p>functions.php</p>\n\n<pre><code>/* Editor styles EXTENDED */\nadd_action('admin_enqueue_scripts', 'load_admin_style');\nfunction load_admin_style() {\n wp_enqueue_style('admin_css', get_stylesheet_directory_uri() .'/gutenberg-styles-extra-wide.css' );\n}\n</code></pre>\n\n<p>gutenberg-styles-extra-wide.css</p>\n\n<pre><code>/*--------------------------------------------------------------\n# 1.0 - Editor\n--------------------------------------------------------------*/\nbody.block-editor-page .edit-post-visual-editor .editor-post-title__block,\nbody.block-editor-page .edit-post-visual-editor .editor-default-block-appender,\nbody.block-editor-page .edit-post-visual-editor .editor-block-list__block {\n max-width: 1200px;\n}\n/* HTML-block */\n.wp-block-html .block-editor-plain-text {\n max-height: 700px;\n font-size: 14px;\n resize: both;\n}\n</code></pre>\n\n<p>Since I am using a child-theme I use get_stylesheet_directory_uri() in functions.php. (get_template_directory_uri() otherwise)\nI also wanted to have more space in the HTML-block.</p>\n\n<p>Thanks for answers and suggestions Tom and Juan.</p>\n\n<p>Takes some time to get used to the Gutenberg editor!</p>\n" }, { "answer_id": 369519, "author": "Luca Reghellin", "author_id": 10381, "author_profile": "https://wordpress.stackexchange.com/users/10381", "pm_score": 0, "selected": false, "text": "<p>A variation on the used action:</p>\n<pre><code>add_action( 'enqueue_block_editor_assets', 'custom_gutenberg_editor_stylesheet' );\nfunction custom_gutenberg_editor_stylesheet() {\n wp_enqueue_style( 'custom-gutenberg-stylesheet', [your css path] . '/gutenberg-styles.css', array(), wp_get_theme()-&gt;get( 'Version' ), 'all' );\n}\n</code></pre>\n<p>then</p>\n<pre><code>.wp-block {\n max-width: 1024px; // whatever\n}\n</code></pre>\n" }, { "answer_id": 373682, "author": "Jason", "author_id": 73096, "author_profile": "https://wordpress.stackexchange.com/users/73096", "pm_score": 0, "selected": false, "text": "<p>My solution was to just add this to your functions.php file:</p>\n<pre><code>add_action('admin_head', 'admin_styles');\nfunction admin_styles() {\n echo '&lt;style&gt;\n .wp-block {max-width: 720px;}\n .wp-block[data-align=&quot;wide&quot;] {max-width: 1280px;}\n &lt;/style&gt;';\n}\n</code></pre>\n" }, { "answer_id": 387256, "author": "Chaz", "author_id": 205510, "author_profile": "https://wordpress.stackexchange.com/users/205510", "pm_score": 1, "selected": false, "text": "<p>If it helps anyone we have developed a free light-weight plugin that lets you control the &quot;Wide width&quot; setting in the Gutenberg block editor and also adds some other optional visual enhancements to make the block edges easier to see.</p>\n<p>To control the &quot;Wide width&quot; setting the plugin enqueues this admin style where [variable] is set in the plugin's settings:</p>\n<pre><code>.wp-block-columns.block-editor-block-list__block.wp-block.block-editor-block-list__layout{max-width:[variable]px!important;}\n</code></pre>\n<p>and also we:</p>\n<pre><code>add_theme_support( 'align-wide' );\n</code></pre>\n<p>The plugin is: <a href=\"https://wordpress.org/plugins/blocksolid/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/blocksolid/</a></p>\n" }, { "answer_id": 402144, "author": "gtamborero", "author_id": 52236, "author_profile": "https://wordpress.stackexchange.com/users/52236", "pm_score": 0, "selected": false, "text": "<p>Try this CSS inside your theme, functions.php:</p>\n<pre><code>// Wider sidebar on gutenberg backend\nfunction my_wider_sidebar() {\necho '\n&lt;style&gt;\n .interface-complementary-area{ width: 450px; }\n&lt;/style&gt;\n';\n}\nadd_action('admin_head', 'my_wider_sidebar');\n</code></pre>\n" } ]
2020/02/20
[ "https://wordpress.stackexchange.com/questions/359092", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3977/" ]
I am new to the Gutenberg editor. Previously I used the Classic editor (plugin) when editing WordPress. The editor area "resized" according to the browser window. With the Gutenberg approach I get a very narrow area to edit in. When I use the HTML-block all I get is a 890px wide and 250px high area with scrollbars. I feel claustrophobic! Are there some way to get around this? Similar question but with no good answers: [Why is the new Gutenberg editor so narrow, and how to make it wider?](https://wordpress.stackexchange.com/questions/338757/why-is-the-new-gutenberg-editor-so-narrow-and-how-to-make-it-wider)
Here is what I did: functions.php ``` /* Editor styles EXTENDED */ add_action('admin_enqueue_scripts', 'load_admin_style'); function load_admin_style() { wp_enqueue_style('admin_css', get_stylesheet_directory_uri() .'/gutenberg-styles-extra-wide.css' ); } ``` gutenberg-styles-extra-wide.css ``` /*-------------------------------------------------------------- # 1.0 - Editor --------------------------------------------------------------*/ body.block-editor-page .edit-post-visual-editor .editor-post-title__block, body.block-editor-page .edit-post-visual-editor .editor-default-block-appender, body.block-editor-page .edit-post-visual-editor .editor-block-list__block { max-width: 1200px; } /* HTML-block */ .wp-block-html .block-editor-plain-text { max-height: 700px; font-size: 14px; resize: both; } ``` Since I am using a child-theme I use get\_stylesheet\_directory\_uri() in functions.php. (get\_template\_directory\_uri() otherwise) I also wanted to have more space in the HTML-block. Thanks for answers and suggestions Tom and Juan. Takes some time to get used to the Gutenberg editor!
359,097
<p>Is there any way to force a Gutenberg block to be on every page of a post type?</p> <p>I tried to add a <strong>template</strong> on my <strong>page</strong> and it does almost what I need, but I can still remove my default blocks.</p> <p>The closest I've come is this:</p> <pre class="lang-php prettyprint-override"><code>function ckt_mina_init_required_block() { // create a new page template (pages only) $page_type_object = get_post_type_object('page'); $page_type_object-&gt;template = [ [ 'core/group', [], [ // add a paragraph block for the page summary [ 'core/paragraph', [ 'placeholder' =&gt; __('Excerpt'), ], ], [ 'core/image', [], ], ], ], ]; $page_type_object-&gt;template_lock = 'all'; } add_action('init', 'ckt_mina_init_required_block'); </code></pre> <p>This will create a new page template and use it on every new page. The 2 blocks "paragraph" and "image" will be present in the first group.</p> <p><strong>But</strong> I cannot add any other block to my page.</p> <p>Or, I can remove the <code>template_lock = 'all'</code>, but then, my blocks can be removed during the page creation.</p> <p>Any idea on how I might achieve to have 2 fixed blocks at the beginning of my Gutenberg area?</p>
[ { "answer_id": 359116, "author": "Vitauts Stočka", "author_id": 181289, "author_profile": "https://wordpress.stackexchange.com/users/181289", "pm_score": 0, "selected": false, "text": "<p>No fast and easy solution for you. Read discussion <a href=\"https://github.com/WordPress/gutenberg/issues/5208\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://github.com/WordPress/gutenberg/issues/8112\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>You may try to write some rather sophisticated Gutenberg code to implement this feature, or maybe you could implement some <code>save_post</code> hook to check saved block structure with <code>parse_blocks</code> and do something if they don't match your required structure. For example, prevent post publication or insert required blocks into content.</p>\n" }, { "answer_id": 407238, "author": "Steve Harwell", "author_id": 223624, "author_profile": "https://wordpress.stackexchange.com/users/223624", "pm_score": 1, "selected": false, "text": "<p>There is a lock feature that can be toggled in the blocks toolbar which is marked up like this. I'm not sure in what version this feature was implemented.</p>\n<pre><code>&lt;!-- wp:paragraph {&quot;lock&quot;:{&quot;move&quot;:true,&quot;remove&quot;:true}} --&gt;\n&lt;p&gt;C1&lt;/p&gt;\n&lt;!-- /wp:paragraph --&gt;\n</code></pre>\n<p>To lock your excerpt paragraph I would do this.</p>\n<pre><code>[\n 'core/paragraph',\n [\n 'placeholder' =&gt; __('Excerpt'),\n 'lock' =&gt; [\n 'move' =&gt; true,\n 'remove' =&gt; true\n ]\n ],\n]\n</code></pre>\n" } ]
2020/02/20
[ "https://wordpress.stackexchange.com/questions/359097", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113538/" ]
Is there any way to force a Gutenberg block to be on every page of a post type? I tried to add a **template** on my **page** and it does almost what I need, but I can still remove my default blocks. The closest I've come is this: ```php function ckt_mina_init_required_block() { // create a new page template (pages only) $page_type_object = get_post_type_object('page'); $page_type_object->template = [ [ 'core/group', [], [ // add a paragraph block for the page summary [ 'core/paragraph', [ 'placeholder' => __('Excerpt'), ], ], [ 'core/image', [], ], ], ], ]; $page_type_object->template_lock = 'all'; } add_action('init', 'ckt_mina_init_required_block'); ``` This will create a new page template and use it on every new page. The 2 blocks "paragraph" and "image" will be present in the first group. **But** I cannot add any other block to my page. Or, I can remove the `template_lock = 'all'`, but then, my blocks can be removed during the page creation. Any idea on how I might achieve to have 2 fixed blocks at the beginning of my Gutenberg area?
There is a lock feature that can be toggled in the blocks toolbar which is marked up like this. I'm not sure in what version this feature was implemented. ``` <!-- wp:paragraph {"lock":{"move":true,"remove":true}} --> <p>C1</p> <!-- /wp:paragraph --> ``` To lock your excerpt paragraph I would do this. ``` [ 'core/paragraph', [ 'placeholder' => __('Excerpt'), 'lock' => [ 'move' => true, 'remove' => true ] ], ] ```
359,104
<p>I have a category called "Featured", but I don't want this category tag to be shown at the bottom of single post pages. I do want to display the other category tags. How do I hide the tag for this one category? </p>
[ { "answer_id": 359116, "author": "Vitauts Stočka", "author_id": 181289, "author_profile": "https://wordpress.stackexchange.com/users/181289", "pm_score": 0, "selected": false, "text": "<p>No fast and easy solution for you. Read discussion <a href=\"https://github.com/WordPress/gutenberg/issues/5208\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://github.com/WordPress/gutenberg/issues/8112\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>You may try to write some rather sophisticated Gutenberg code to implement this feature, or maybe you could implement some <code>save_post</code> hook to check saved block structure with <code>parse_blocks</code> and do something if they don't match your required structure. For example, prevent post publication or insert required blocks into content.</p>\n" }, { "answer_id": 407238, "author": "Steve Harwell", "author_id": 223624, "author_profile": "https://wordpress.stackexchange.com/users/223624", "pm_score": 1, "selected": false, "text": "<p>There is a lock feature that can be toggled in the blocks toolbar which is marked up like this. I'm not sure in what version this feature was implemented.</p>\n<pre><code>&lt;!-- wp:paragraph {&quot;lock&quot;:{&quot;move&quot;:true,&quot;remove&quot;:true}} --&gt;\n&lt;p&gt;C1&lt;/p&gt;\n&lt;!-- /wp:paragraph --&gt;\n</code></pre>\n<p>To lock your excerpt paragraph I would do this.</p>\n<pre><code>[\n 'core/paragraph',\n [\n 'placeholder' =&gt; __('Excerpt'),\n 'lock' =&gt; [\n 'move' =&gt; true,\n 'remove' =&gt; true\n ]\n ],\n]\n</code></pre>\n" } ]
2020/02/20
[ "https://wordpress.stackexchange.com/questions/359104", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69240/" ]
I have a category called "Featured", but I don't want this category tag to be shown at the bottom of single post pages. I do want to display the other category tags. How do I hide the tag for this one category?
There is a lock feature that can be toggled in the blocks toolbar which is marked up like this. I'm not sure in what version this feature was implemented. ``` <!-- wp:paragraph {"lock":{"move":true,"remove":true}} --> <p>C1</p> <!-- /wp:paragraph --> ``` To lock your excerpt paragraph I would do this. ``` [ 'core/paragraph', [ 'placeholder' => __('Excerpt'), 'lock' => [ 'move' => true, 'remove' => true ] ], ] ```
359,127
<p>I use following function to get my custom posts ordering by title</p> <pre><code>$posts = get_posts( array( "orderby"=&gt; "title", "order" =&gt; "ASC", "post_type" =&gt; "my-custom-post-type", "posts_per_page" =&gt; -1, "fields" =&gt; "ids", "meta_query" =&gt; array( array( "key" =&gt; "ams_park_id", "value" =&gt; get_the_ID(), ) ) ) ); </code></pre> <p>And it orders by title, the problem is that i have one posts that have is titled: "It's a small world", and this is being ordered at the beginning of the list.</p> <p>Example of the current returning list:</p> <pre><code>0 - "It's a small world" 1 - Albatross 2 - Alligator 3 - Baboon 4 - Camel 5 - Fox 6 - Hino 7 - Iguana 8 - Jackal 9... </code></pre> <p>How can i make to make the selector ignore the quote and send it to the "i" part of the order? Example:</p> <pre><code>0 - Albatross 1 - Alligator 2 - Baboon 3 - Camel 4 - Fox 5 - Hino 6 - Iguana 7 - "It's a small world" 8 - Jackal 9... </code></pre>
[ { "answer_id": 360034, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 5, "selected": true, "text": "<p>Try this...</p>\n\n<pre><code>$posts = get_posts(\n array(\n \"orderby\"=&gt; \"slug\",\n \"order\" =&gt; \"ASC\",\n \"post_type\" =&gt; \"my-custom-post-type\",\n \"posts_per_page\" =&gt; -1,\n \"fields\" =&gt; \"ids\",\n \"meta_query\" =&gt; array(\n array(\n \"key\" =&gt; \"ams_park_id\",\n \"value\" =&gt; get_the_ID(),\n )\n )\n )\n);\n</code></pre>\n\n<p>Noticed I changed <code>\"orderby\"=&gt; \"title\",</code> to <code>\"orderby\"=&gt; \"slug\"</code>. Typically the slug will be close to the title but all of the special characters will be removed.</p>\n" }, { "answer_id": 360267, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>The answer which sorts with slug in stead of title will work fine as long as you are sure the slug really correspondents with the title. Otherwise it is safer to retrieve <code>$posts</code> unsorted from the database and use <code>PHP</code>'s <a href=\"https://www.php.net/manual/en/function.uasort.php\" rel=\"nofollow noreferrer\"><code>uasort</code></a> command for custom sorting. Like this:</p>\n\n<pre><code>function wpse359127_custom_sort ($post_a,$post_b) {\n // Pick the component of the post object you want to use for comparison\n $title_a = $post_a-&gt;post_title;\n $title_b = $post_b-&gt;post_title;\n // Remove any character that isn't A-Z, a-z or 0-9.\n // Or maybe do more complex things if you language has ö's, for instance\n $title_a = preg_replace(\"/[^A-Za-z0-9]/\", '', $title_a);\n $title_b = preg_replace(\"/[^A-Za-z0-9]/\", '', $title_b);\n // Return -1 of 1 depending on which post needs to be in front of the queue\n if ($title_a &lt; $title_b) return -1; else return 1;\n }\n\nuasort ($posts, 'wpse359127_custom_sort');\n</code></pre>\n\n<p>Note: I didn't test this code, so it might be buggy. </p>\n" }, { "answer_id": 360280, "author": "brett", "author_id": 136481, "author_profile": "https://wordpress.stackexchange.com/users/136481", "pm_score": 0, "selected": false, "text": "<p>You could duplicate the title field by hooking into save_post and store the title value (minus the offending characters) into a custom field (let’s say we name the field clean_title).\nIn your original query you would then sort by this custom field instead of title.</p>\n\n<p>Additionally you would need to write a function to be run once in which you loop over all posts and initialize the clean_title field by copying the cleaned title to it.</p>\n" } ]
2020/02/20
[ "https://wordpress.stackexchange.com/questions/359127", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130208/" ]
I use following function to get my custom posts ordering by title ``` $posts = get_posts( array( "orderby"=> "title", "order" => "ASC", "post_type" => "my-custom-post-type", "posts_per_page" => -1, "fields" => "ids", "meta_query" => array( array( "key" => "ams_park_id", "value" => get_the_ID(), ) ) ) ); ``` And it orders by title, the problem is that i have one posts that have is titled: "It's a small world", and this is being ordered at the beginning of the list. Example of the current returning list: ``` 0 - "It's a small world" 1 - Albatross 2 - Alligator 3 - Baboon 4 - Camel 5 - Fox 6 - Hino 7 - Iguana 8 - Jackal 9... ``` How can i make to make the selector ignore the quote and send it to the "i" part of the order? Example: ``` 0 - Albatross 1 - Alligator 2 - Baboon 3 - Camel 4 - Fox 5 - Hino 6 - Iguana 7 - "It's a small world" 8 - Jackal 9... ```
Try this... ``` $posts = get_posts( array( "orderby"=> "slug", "order" => "ASC", "post_type" => "my-custom-post-type", "posts_per_page" => -1, "fields" => "ids", "meta_query" => array( array( "key" => "ams_park_id", "value" => get_the_ID(), ) ) ) ); ``` Noticed I changed `"orderby"=> "title",` to `"orderby"=> "slug"`. Typically the slug will be close to the title but all of the special characters will be removed.
359,163
<p>I'm trying to make this as simple as possible just to get the basics down, but I keep getting a 400 error and 0 response from admin-ajax.php. I just want to hit ajax with some data. Here's my js:</p> <pre><code>jQuery(document).ready(function($) { $('body').click(function(e){ $.ajax({ action: 'the_ajax_hook', data: 'field=data', type: 'post', url: the_ajax_script.ajaxurl, success: function(response_from_the_action_function) { $("#site-content").html(response_from_the_action_function); } }); }); }); </code></pre> <p>And here's my plugin:</p> <pre><code>function load_my_scripts(){ wp_enqueue_script( 'my-ajax-handle', plugin_dir_url( __FILE__ ) . 'ajax.js', array( 'jquery' ) ); wp_localize_script( 'my-ajax-handle', 'the_ajax_script', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ) ) ); } add_action( 'wp_enqueue_scripts', 'load_my_scripts' ); add_action( 'wp_ajax_the_ajax_hook', 'the_action_function' ); add_action( 'wp_ajax_nopriv_the_ajax_hook', 'the_action_function' ); function the_action_function(){ echo "field is " . $_POST['field']; die(); } </code></pre> <p>The localization seems to work because it hits the right URL for admin_ajax, but it's a bad request and returns nothing.</p> <p>I know I'm missing something obvious but that's the thing about obvious mistakes, they don't seem obvious until someone else shows it to you. What am I missing?</p>
[ { "answer_id": 359165, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 1, "selected": true, "text": "<p>From codex: <a href=\"https://developer.wordpress.org/reference/hooks/wp_ajax_action/\" rel=\"nofollow noreferrer\">wp_ajax_{$action}</a> and wp_ajax_nopriv{$action}\nthe dinamic part {$action} must be the same name as the function, so instead of:</p>\n\n<pre><code>add_action( 'wp_ajax_the_ajax_hook', 'the_action_function' );\nadd_action( 'wp_ajax_nopriv_the_ajax_hook', 'the_action_function' );\n</code></pre>\n\n<p>do:</p>\n\n<pre><code>add_action( 'wp_ajax_the_action_function', 'the_action_function' );\nadd_action( 'wp_ajax_nopriv_the_action_function', 'the_action_function' );\n</code></pre>\n" }, { "answer_id": 359176, "author": "Chetan Vaghela", "author_id": 169856, "author_profile": "https://wordpress.stackexchange.com/users/169856", "pm_score": 1, "selected": false, "text": "<p>You should pass data as <code>data: {action: 'actionname', filed: data},</code>. So your data is variable which contain data. So your code look like below:</p>\n\n<pre><code>jQuery(document).ready(function($) {\n $('body').click(function(e){\n $.ajax({\n data: {\n action: 'the_ajax_hook',\n field: data,\n },\n type: 'post',\n url: ajax_object.ajaxurl,\n success: function(response_from_the_action_function) {\n $(\"#site-content\").html(response_from_the_action_function);\n }\n });\n });\n});\n</code></pre>\n" } ]
2020/02/21
[ "https://wordpress.stackexchange.com/questions/359163", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183099/" ]
I'm trying to make this as simple as possible just to get the basics down, but I keep getting a 400 error and 0 response from admin-ajax.php. I just want to hit ajax with some data. Here's my js: ``` jQuery(document).ready(function($) { $('body').click(function(e){ $.ajax({ action: 'the_ajax_hook', data: 'field=data', type: 'post', url: the_ajax_script.ajaxurl, success: function(response_from_the_action_function) { $("#site-content").html(response_from_the_action_function); } }); }); }); ``` And here's my plugin: ``` function load_my_scripts(){ wp_enqueue_script( 'my-ajax-handle', plugin_dir_url( __FILE__ ) . 'ajax.js', array( 'jquery' ) ); wp_localize_script( 'my-ajax-handle', 'the_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); } add_action( 'wp_enqueue_scripts', 'load_my_scripts' ); add_action( 'wp_ajax_the_ajax_hook', 'the_action_function' ); add_action( 'wp_ajax_nopriv_the_ajax_hook', 'the_action_function' ); function the_action_function(){ echo "field is " . $_POST['field']; die(); } ``` The localization seems to work because it hits the right URL for admin\_ajax, but it's a bad request and returns nothing. I know I'm missing something obvious but that's the thing about obvious mistakes, they don't seem obvious until someone else shows it to you. What am I missing?
From codex: [wp\_ajax\_{$action}](https://developer.wordpress.org/reference/hooks/wp_ajax_action/) and wp\_ajax\_nopriv{$action} the dinamic part {$action} must be the same name as the function, so instead of: ``` add_action( 'wp_ajax_the_ajax_hook', 'the_action_function' ); add_action( 'wp_ajax_nopriv_the_ajax_hook', 'the_action_function' ); ``` do: ``` add_action( 'wp_ajax_the_action_function', 'the_action_function' ); add_action( 'wp_ajax_nopriv_the_action_function', 'the_action_function' ); ```
359,171
<p>Good Morning,</p> <p>I use Events Calendar for our Website, now I want to change the "Now onwards" and "onwards" on top of the page, also the next and previous at the bottom of the event calendar. I already tried to change it with their documentation (and support) but it didn't work. As we are a German business without English business Connections we don't want to have some English text on our page.. Thank you in advance.</p>
[ { "answer_id": 359175, "author": "GarethTF", "author_id": 181549, "author_profile": "https://wordpress.stackexchange.com/users/181549", "pm_score": 0, "selected": false, "text": "<p>For only a couple of words I would use the gettext filter e.g.</p>\n\n<pre><code>function wse_text_filter( $translated_text, $untranslated_text ) {\n switch( $untranslated_text ) {\n\n case 'Now onwards':\n $translated_text = __( 'Now backwards','text_domain' );\n break;\n\n case 'onwards':\n $translated_text = __( 'Backwards','text_domain' );\n break;\n\n }\n return $translated_text;\n}\nadd_filter('gettext', 'wse_text_filter', 20, 3);\n</code></pre>\n\n<p>It's hopefully pretty self explanatory, you could also try language switching plugins such as Polyang or WPML.</p>\n" }, { "answer_id": 366969, "author": "Kevin Marsden", "author_id": 19985, "author_profile": "https://wordpress.stackexchange.com/users/19985", "pm_score": 1, "selected": false, "text": "<p>The \"Now onwards\" string is translated with <a href=\"https://developer.wordpress.org/reference/functions/_x/\" rel=\"nofollow noreferrer\">_x()</a> which is different than __() because it allows context to be added to the string being translated. </p>\n\n<p>Because there is context, you need to use <a href=\"https://developer.wordpress.org/reference/hooks/gettext_with_context/\" rel=\"nofollow noreferrer\">gettext_with_context</a> instead of gettext. Here's a simple example based on the one in the WP.org Code Reference:</p>\n\n<pre><code>function example_gettext_with_context( $translated, $text ) {\n if ( 'Now' == $text ) {\n $translated = 'Today';\n }\n\n return $translated;\n}\nadd_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 2 );\n</code></pre>\n\n<p>You can find the relavent code in the Events Calendar plugin <a href=\"https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L49\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L158\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p><a href=\"https://theeventscalendar.com/knowledgebase/k/change-the-wording-of-any-bit-of-text-or-string/\" rel=\"nofollow noreferrer\">The Events Calendar website</a> also has some detailed examples. </p>\n" } ]
2020/02/21
[ "https://wordpress.stackexchange.com/questions/359171", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183105/" ]
Good Morning, I use Events Calendar for our Website, now I want to change the "Now onwards" and "onwards" on top of the page, also the next and previous at the bottom of the event calendar. I already tried to change it with their documentation (and support) but it didn't work. As we are a German business without English business Connections we don't want to have some English text on our page.. Thank you in advance.
The "Now onwards" string is translated with [\_x()](https://developer.wordpress.org/reference/functions/_x/) which is different than \_\_() because it allows context to be added to the string being translated. Because there is context, you need to use [gettext\_with\_context](https://developer.wordpress.org/reference/hooks/gettext_with_context/) instead of gettext. Here's a simple example based on the one in the WP.org Code Reference: ``` function example_gettext_with_context( $translated, $text ) { if ( 'Now' == $text ) { $translated = 'Today'; } return $translated; } add_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 2 ); ``` You can find the relavent code in the Events Calendar plugin [here](https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L49) and [here](https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L158) [The Events Calendar website](https://theeventscalendar.com/knowledgebase/k/change-the-wording-of-any-bit-of-text-or-string/) also has some detailed examples.
359,174
<p>I am trying to apply a format to the selected text, but the apply format method of gutenberg doesnt return any error and fails silently.</p> <p>I am registering my format type like this</p> <pre><code>import { registerFormatType } from "@wordpress/rich-text"; registerFormatType(BLOCK_NAME, { title: "Answer", tagName: "span", className: SOME_CLASS }); </code></pre> <p>and trying to apply like this</p> <pre><code> on(SOME_EVENT, result =&gt; { applyFormat(props.value, { type: BLOCK_NAME }); } </code></pre> <p>The applyformat method doesn't throw any errors but when i try to apply the format to the text selection it didnt create the wrapper around it.It fails silently, any reason why its not working?</p> <p><strong>Update:</strong> I did a console.log on result from apply format, but it didnt return the formatted text.</p> <pre><code>const result = applyFormat(props.value, { type: BLOCK_NAME }); console.log(result) </code></pre> <p>props.value in console</p> <pre><code>{formats: Array(16), text: "qwe qwewq eqweq?", start: 4, end: 11} </code></pre> <p>value of result from applyFormat</p> <pre><code>{formats: Array(16), text: "qwe qwewq eqweq?", start: 4, end: 11} </code></pre> <p>I expect the applyFormat to add a span with a class name around the selected text, what am i doing wrong in the code?</p>
[ { "answer_id": 359175, "author": "GarethTF", "author_id": 181549, "author_profile": "https://wordpress.stackexchange.com/users/181549", "pm_score": 0, "selected": false, "text": "<p>For only a couple of words I would use the gettext filter e.g.</p>\n\n<pre><code>function wse_text_filter( $translated_text, $untranslated_text ) {\n switch( $untranslated_text ) {\n\n case 'Now onwards':\n $translated_text = __( 'Now backwards','text_domain' );\n break;\n\n case 'onwards':\n $translated_text = __( 'Backwards','text_domain' );\n break;\n\n }\n return $translated_text;\n}\nadd_filter('gettext', 'wse_text_filter', 20, 3);\n</code></pre>\n\n<p>It's hopefully pretty self explanatory, you could also try language switching plugins such as Polyang or WPML.</p>\n" }, { "answer_id": 366969, "author": "Kevin Marsden", "author_id": 19985, "author_profile": "https://wordpress.stackexchange.com/users/19985", "pm_score": 1, "selected": false, "text": "<p>The \"Now onwards\" string is translated with <a href=\"https://developer.wordpress.org/reference/functions/_x/\" rel=\"nofollow noreferrer\">_x()</a> which is different than __() because it allows context to be added to the string being translated. </p>\n\n<p>Because there is context, you need to use <a href=\"https://developer.wordpress.org/reference/hooks/gettext_with_context/\" rel=\"nofollow noreferrer\">gettext_with_context</a> instead of gettext. Here's a simple example based on the one in the WP.org Code Reference:</p>\n\n<pre><code>function example_gettext_with_context( $translated, $text ) {\n if ( 'Now' == $text ) {\n $translated = 'Today';\n }\n\n return $translated;\n}\nadd_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 2 );\n</code></pre>\n\n<p>You can find the relavent code in the Events Calendar plugin <a href=\"https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L49\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L158\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p><a href=\"https://theeventscalendar.com/knowledgebase/k/change-the-wording-of-any-bit-of-text-or-string/\" rel=\"nofollow noreferrer\">The Events Calendar website</a> also has some detailed examples. </p>\n" } ]
2020/02/21
[ "https://wordpress.stackexchange.com/questions/359174", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/180218/" ]
I am trying to apply a format to the selected text, but the apply format method of gutenberg doesnt return any error and fails silently. I am registering my format type like this ``` import { registerFormatType } from "@wordpress/rich-text"; registerFormatType(BLOCK_NAME, { title: "Answer", tagName: "span", className: SOME_CLASS }); ``` and trying to apply like this ``` on(SOME_EVENT, result => { applyFormat(props.value, { type: BLOCK_NAME }); } ``` The applyformat method doesn't throw any errors but when i try to apply the format to the text selection it didnt create the wrapper around it.It fails silently, any reason why its not working? **Update:** I did a console.log on result from apply format, but it didnt return the formatted text. ``` const result = applyFormat(props.value, { type: BLOCK_NAME }); console.log(result) ``` props.value in console ``` {formats: Array(16), text: "qwe qwewq eqweq?", start: 4, end: 11} ``` value of result from applyFormat ``` {formats: Array(16), text: "qwe qwewq eqweq?", start: 4, end: 11} ``` I expect the applyFormat to add a span with a class name around the selected text, what am i doing wrong in the code?
The "Now onwards" string is translated with [\_x()](https://developer.wordpress.org/reference/functions/_x/) which is different than \_\_() because it allows context to be added to the string being translated. Because there is context, you need to use [gettext\_with\_context](https://developer.wordpress.org/reference/hooks/gettext_with_context/) instead of gettext. Here's a simple example based on the one in the WP.org Code Reference: ``` function example_gettext_with_context( $translated, $text ) { if ( 'Now' == $text ) { $translated = 'Today'; } return $translated; } add_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 2 ); ``` You can find the relavent code in the Events Calendar plugin [here](https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L49) and [here](https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L158) [The Events Calendar website](https://theeventscalendar.com/knowledgebase/k/change-the-wording-of-any-bit-of-text-or-string/) also has some detailed examples.
359,186
<p>Can't figure out why this isn't working. I'm trying to query posts for a member mailing list and simply don't want to include users that are not members. Right now even the users that have an empty meta_value to the meta_key 'member' are shown. Please help! (WP version 5.3.2)</p> <pre><code> function get_all_users () { $args = array( 'orderby' =&gt; 'display_name', 'meta_query' =&gt; array ( array ( 'key' =&gt; 'member', 'value' =&gt; '', 'compare' =&gt; '!=' ) ) ); $users = get_users($args); ob_start(); // Array of WP_User objects. foreach ( $users as $user ) { $firstName = get_user_meta($user-&gt;ID, 'first_name', true); $lastName = get_user_meta($user-&gt;ID, 'last_name', true); echo "&lt;li&gt;&lt;a href=\"mailto:" . $user-&gt;user_email . "\"&gt;" . $firstName . " " . $lastName . "&lt;/a&gt;&lt;/li&gt;"; } return ob_get_clean(); } </code></pre>
[ { "answer_id": 359175, "author": "GarethTF", "author_id": 181549, "author_profile": "https://wordpress.stackexchange.com/users/181549", "pm_score": 0, "selected": false, "text": "<p>For only a couple of words I would use the gettext filter e.g.</p>\n\n<pre><code>function wse_text_filter( $translated_text, $untranslated_text ) {\n switch( $untranslated_text ) {\n\n case 'Now onwards':\n $translated_text = __( 'Now backwards','text_domain' );\n break;\n\n case 'onwards':\n $translated_text = __( 'Backwards','text_domain' );\n break;\n\n }\n return $translated_text;\n}\nadd_filter('gettext', 'wse_text_filter', 20, 3);\n</code></pre>\n\n<p>It's hopefully pretty self explanatory, you could also try language switching plugins such as Polyang or WPML.</p>\n" }, { "answer_id": 366969, "author": "Kevin Marsden", "author_id": 19985, "author_profile": "https://wordpress.stackexchange.com/users/19985", "pm_score": 1, "selected": false, "text": "<p>The \"Now onwards\" string is translated with <a href=\"https://developer.wordpress.org/reference/functions/_x/\" rel=\"nofollow noreferrer\">_x()</a> which is different than __() because it allows context to be added to the string being translated. </p>\n\n<p>Because there is context, you need to use <a href=\"https://developer.wordpress.org/reference/hooks/gettext_with_context/\" rel=\"nofollow noreferrer\">gettext_with_context</a> instead of gettext. Here's a simple example based on the one in the WP.org Code Reference:</p>\n\n<pre><code>function example_gettext_with_context( $translated, $text ) {\n if ( 'Now' == $text ) {\n $translated = 'Today';\n }\n\n return $translated;\n}\nadd_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 2 );\n</code></pre>\n\n<p>You can find the relavent code in the Events Calendar plugin <a href=\"https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L49\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L158\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p><a href=\"https://theeventscalendar.com/knowledgebase/k/change-the-wording-of-any-bit-of-text-or-string/\" rel=\"nofollow noreferrer\">The Events Calendar website</a> also has some detailed examples. </p>\n" } ]
2020/02/21
[ "https://wordpress.stackexchange.com/questions/359186", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/164427/" ]
Can't figure out why this isn't working. I'm trying to query posts for a member mailing list and simply don't want to include users that are not members. Right now even the users that have an empty meta\_value to the meta\_key 'member' are shown. Please help! (WP version 5.3.2) ``` function get_all_users () { $args = array( 'orderby' => 'display_name', 'meta_query' => array ( array ( 'key' => 'member', 'value' => '', 'compare' => '!=' ) ) ); $users = get_users($args); ob_start(); // Array of WP_User objects. foreach ( $users as $user ) { $firstName = get_user_meta($user->ID, 'first_name', true); $lastName = get_user_meta($user->ID, 'last_name', true); echo "<li><a href=\"mailto:" . $user->user_email . "\">" . $firstName . " " . $lastName . "</a></li>"; } return ob_get_clean(); } ```
The "Now onwards" string is translated with [\_x()](https://developer.wordpress.org/reference/functions/_x/) which is different than \_\_() because it allows context to be added to the string being translated. Because there is context, you need to use [gettext\_with\_context](https://developer.wordpress.org/reference/hooks/gettext_with_context/) instead of gettext. Here's a simple example based on the one in the WP.org Code Reference: ``` function example_gettext_with_context( $translated, $text ) { if ( 'Now' == $text ) { $translated = 'Today'; } return $translated; } add_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 2 ); ``` You can find the relavent code in the Events Calendar plugin [here](https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L49) and [here](https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L158) [The Events Calendar website](https://theeventscalendar.com/knowledgebase/k/change-the-wording-of-any-bit-of-text-or-string/) also has some detailed examples.
359,213
<p>I am trying to add Wordpress featured image in tag. I used these 3 shortcodes.</p> <pre><code>&lt;?php echo $image_large[0]; ?&gt; &lt;?php echo get_the_post_thumbnail(null,'thumbnail');?&gt; &lt;?php echo get_the_post_thumbnail( $page-&gt;ID, 'full' ); ?&gt; </code></pre> <p>Example</p> <pre><code>&lt;a href="&lt;?php echo get_the_post_thumbnail( $page-&gt;ID, 'full' ); ?&gt;" &gt;View Larger&lt;/a&gt; </code></pre> <p>But nothing working. Please help me ... </p>
[ { "answer_id": 359175, "author": "GarethTF", "author_id": 181549, "author_profile": "https://wordpress.stackexchange.com/users/181549", "pm_score": 0, "selected": false, "text": "<p>For only a couple of words I would use the gettext filter e.g.</p>\n\n<pre><code>function wse_text_filter( $translated_text, $untranslated_text ) {\n switch( $untranslated_text ) {\n\n case 'Now onwards':\n $translated_text = __( 'Now backwards','text_domain' );\n break;\n\n case 'onwards':\n $translated_text = __( 'Backwards','text_domain' );\n break;\n\n }\n return $translated_text;\n}\nadd_filter('gettext', 'wse_text_filter', 20, 3);\n</code></pre>\n\n<p>It's hopefully pretty self explanatory, you could also try language switching plugins such as Polyang or WPML.</p>\n" }, { "answer_id": 366969, "author": "Kevin Marsden", "author_id": 19985, "author_profile": "https://wordpress.stackexchange.com/users/19985", "pm_score": 1, "selected": false, "text": "<p>The \"Now onwards\" string is translated with <a href=\"https://developer.wordpress.org/reference/functions/_x/\" rel=\"nofollow noreferrer\">_x()</a> which is different than __() because it allows context to be added to the string being translated. </p>\n\n<p>Because there is context, you need to use <a href=\"https://developer.wordpress.org/reference/hooks/gettext_with_context/\" rel=\"nofollow noreferrer\">gettext_with_context</a> instead of gettext. Here's a simple example based on the one in the WP.org Code Reference:</p>\n\n<pre><code>function example_gettext_with_context( $translated, $text ) {\n if ( 'Now' == $text ) {\n $translated = 'Today';\n }\n\n return $translated;\n}\nadd_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 2 );\n</code></pre>\n\n<p>You can find the relavent code in the Events Calendar plugin <a href=\"https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L49\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L158\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p><a href=\"https://theeventscalendar.com/knowledgebase/k/change-the-wording-of-any-bit-of-text-or-string/\" rel=\"nofollow noreferrer\">The Events Calendar website</a> also has some detailed examples. </p>\n" } ]
2020/02/21
[ "https://wordpress.stackexchange.com/questions/359213", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183135/" ]
I am trying to add Wordpress featured image in tag. I used these 3 shortcodes. ``` <?php echo $image_large[0]; ?> <?php echo get_the_post_thumbnail(null,'thumbnail');?> <?php echo get_the_post_thumbnail( $page->ID, 'full' ); ?> ``` Example ``` <a href="<?php echo get_the_post_thumbnail( $page->ID, 'full' ); ?>" >View Larger</a> ``` But nothing working. Please help me ...
The "Now onwards" string is translated with [\_x()](https://developer.wordpress.org/reference/functions/_x/) which is different than \_\_() because it allows context to be added to the string being translated. Because there is context, you need to use [gettext\_with\_context](https://developer.wordpress.org/reference/hooks/gettext_with_context/) instead of gettext. Here's a simple example based on the one in the WP.org Code Reference: ``` function example_gettext_with_context( $translated, $text ) { if ( 'Now' == $text ) { $translated = 'Today'; } return $translated; } add_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 2 ); ``` You can find the relavent code in the Events Calendar plugin [here](https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L49) and [here](https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L158) [The Events Calendar website](https://theeventscalendar.com/knowledgebase/k/change-the-wording-of-any-bit-of-text-or-string/) also has some detailed examples.
359,215
<p>Im currently using User Role editor to modify permission for the user role. I'd like to be able to restrict the role from publishing a post. They can save the draft but they should not be able to publish. Is there a better way to do it?</p>
[ { "answer_id": 359175, "author": "GarethTF", "author_id": 181549, "author_profile": "https://wordpress.stackexchange.com/users/181549", "pm_score": 0, "selected": false, "text": "<p>For only a couple of words I would use the gettext filter e.g.</p>\n\n<pre><code>function wse_text_filter( $translated_text, $untranslated_text ) {\n switch( $untranslated_text ) {\n\n case 'Now onwards':\n $translated_text = __( 'Now backwards','text_domain' );\n break;\n\n case 'onwards':\n $translated_text = __( 'Backwards','text_domain' );\n break;\n\n }\n return $translated_text;\n}\nadd_filter('gettext', 'wse_text_filter', 20, 3);\n</code></pre>\n\n<p>It's hopefully pretty self explanatory, you could also try language switching plugins such as Polyang or WPML.</p>\n" }, { "answer_id": 366969, "author": "Kevin Marsden", "author_id": 19985, "author_profile": "https://wordpress.stackexchange.com/users/19985", "pm_score": 1, "selected": false, "text": "<p>The \"Now onwards\" string is translated with <a href=\"https://developer.wordpress.org/reference/functions/_x/\" rel=\"nofollow noreferrer\">_x()</a> which is different than __() because it allows context to be added to the string being translated. </p>\n\n<p>Because there is context, you need to use <a href=\"https://developer.wordpress.org/reference/hooks/gettext_with_context/\" rel=\"nofollow noreferrer\">gettext_with_context</a> instead of gettext. Here's a simple example based on the one in the WP.org Code Reference:</p>\n\n<pre><code>function example_gettext_with_context( $translated, $text ) {\n if ( 'Now' == $text ) {\n $translated = 'Today';\n }\n\n return $translated;\n}\nadd_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 2 );\n</code></pre>\n\n<p>You can find the relavent code in the Events Calendar plugin <a href=\"https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L49\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L158\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p><a href=\"https://theeventscalendar.com/knowledgebase/k/change-the-wording-of-any-bit-of-text-or-string/\" rel=\"nofollow noreferrer\">The Events Calendar website</a> also has some detailed examples. </p>\n" } ]
2020/02/21
[ "https://wordpress.stackexchange.com/questions/359215", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101716/" ]
Im currently using User Role editor to modify permission for the user role. I'd like to be able to restrict the role from publishing a post. They can save the draft but they should not be able to publish. Is there a better way to do it?
The "Now onwards" string is translated with [\_x()](https://developer.wordpress.org/reference/functions/_x/) which is different than \_\_() because it allows context to be added to the string being translated. Because there is context, you need to use [gettext\_with\_context](https://developer.wordpress.org/reference/hooks/gettext_with_context/) instead of gettext. Here's a simple example based on the one in the WP.org Code Reference: ``` function example_gettext_with_context( $translated, $text ) { if ( 'Now' == $text ) { $translated = 'Today'; } return $translated; } add_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 2 ); ``` You can find the relavent code in the Events Calendar plugin [here](https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L49) and [here](https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L158) [The Events Calendar website](https://theeventscalendar.com/knowledgebase/k/change-the-wording-of-any-bit-of-text-or-string/) also has some detailed examples.
359,221
<p>I'm getting <code>Error establishing a database connection</code> when installing WP.</p> <p>The following prints "Connected" when putting into <code>wp-config.php</code>:</p> <pre><code>$mysqli_connection = mysqli_connect( $_dbsettings['host'], $_dbsettings['user'], $_dbsettings['pass'], trim( $_dbsettings['path'], '/' ), $_dbsettings['port'] ); if ($mysqli_connection-&gt;connect_error) { echo "Not connected, error: " . $mysqli_connection-&gt;connect_error; } else { echo "Connected."; } </code></pre> <p>What's going on?</p> <p>Update:</p> <p>I use <a href="https://github.com/xyu/heroku-wp" rel="nofollow noreferrer">heroku-wp</a>, more about the <code>wp-config.php</code> <a href="https://github.com/xyu/heroku-wp/blob/master/public/wp-config.php" rel="nofollow noreferrer">here</a>.</p>
[ { "answer_id": 359175, "author": "GarethTF", "author_id": 181549, "author_profile": "https://wordpress.stackexchange.com/users/181549", "pm_score": 0, "selected": false, "text": "<p>For only a couple of words I would use the gettext filter e.g.</p>\n\n<pre><code>function wse_text_filter( $translated_text, $untranslated_text ) {\n switch( $untranslated_text ) {\n\n case 'Now onwards':\n $translated_text = __( 'Now backwards','text_domain' );\n break;\n\n case 'onwards':\n $translated_text = __( 'Backwards','text_domain' );\n break;\n\n }\n return $translated_text;\n}\nadd_filter('gettext', 'wse_text_filter', 20, 3);\n</code></pre>\n\n<p>It's hopefully pretty self explanatory, you could also try language switching plugins such as Polyang or WPML.</p>\n" }, { "answer_id": 366969, "author": "Kevin Marsden", "author_id": 19985, "author_profile": "https://wordpress.stackexchange.com/users/19985", "pm_score": 1, "selected": false, "text": "<p>The \"Now onwards\" string is translated with <a href=\"https://developer.wordpress.org/reference/functions/_x/\" rel=\"nofollow noreferrer\">_x()</a> which is different than __() because it allows context to be added to the string being translated. </p>\n\n<p>Because there is context, you need to use <a href=\"https://developer.wordpress.org/reference/hooks/gettext_with_context/\" rel=\"nofollow noreferrer\">gettext_with_context</a> instead of gettext. Here's a simple example based on the one in the WP.org Code Reference:</p>\n\n<pre><code>function example_gettext_with_context( $translated, $text ) {\n if ( 'Now' == $text ) {\n $translated = 'Today';\n }\n\n return $translated;\n}\nadd_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 2 );\n</code></pre>\n\n<p>You can find the relavent code in the Events Calendar plugin <a href=\"https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L49\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L158\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p><a href=\"https://theeventscalendar.com/knowledgebase/k/change-the-wording-of-any-bit-of-text-or-string/\" rel=\"nofollow noreferrer\">The Events Calendar website</a> also has some detailed examples. </p>\n" } ]
2020/02/21
[ "https://wordpress.stackexchange.com/questions/359221", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/155818/" ]
I'm getting `Error establishing a database connection` when installing WP. The following prints "Connected" when putting into `wp-config.php`: ``` $mysqli_connection = mysqli_connect( $_dbsettings['host'], $_dbsettings['user'], $_dbsettings['pass'], trim( $_dbsettings['path'], '/' ), $_dbsettings['port'] ); if ($mysqli_connection->connect_error) { echo "Not connected, error: " . $mysqli_connection->connect_error; } else { echo "Connected."; } ``` What's going on? Update: I use [heroku-wp](https://github.com/xyu/heroku-wp), more about the `wp-config.php` [here](https://github.com/xyu/heroku-wp/blob/master/public/wp-config.php).
The "Now onwards" string is translated with [\_x()](https://developer.wordpress.org/reference/functions/_x/) which is different than \_\_() because it allows context to be added to the string being translated. Because there is context, you need to use [gettext\_with\_context](https://developer.wordpress.org/reference/hooks/gettext_with_context/) instead of gettext. Here's a simple example based on the one in the WP.org Code Reference: ``` function example_gettext_with_context( $translated, $text ) { if ( 'Now' == $text ) { $translated = 'Today'; } return $translated; } add_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 2 ); ``` You can find the relavent code in the Events Calendar plugin [here](https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L49) and [here](https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L158) [The Events Calendar website](https://theeventscalendar.com/knowledgebase/k/change-the-wording-of-any-bit-of-text-or-string/) also has some detailed examples.
359,286
<p>I would like to remove the category title or tag from my individual posts on my archive pages. I have already succeeded in removing the tags from the homepage and archive page header but they still show up on the individual posts (they are in a red font). So the posts always have the category "Latest Post" next to the actual headline, for instance. I am using the Newsliner theme if that helps. Thanks</p>
[ { "answer_id": 359175, "author": "GarethTF", "author_id": 181549, "author_profile": "https://wordpress.stackexchange.com/users/181549", "pm_score": 0, "selected": false, "text": "<p>For only a couple of words I would use the gettext filter e.g.</p>\n\n<pre><code>function wse_text_filter( $translated_text, $untranslated_text ) {\n switch( $untranslated_text ) {\n\n case 'Now onwards':\n $translated_text = __( 'Now backwards','text_domain' );\n break;\n\n case 'onwards':\n $translated_text = __( 'Backwards','text_domain' );\n break;\n\n }\n return $translated_text;\n}\nadd_filter('gettext', 'wse_text_filter', 20, 3);\n</code></pre>\n\n<p>It's hopefully pretty self explanatory, you could also try language switching plugins such as Polyang or WPML.</p>\n" }, { "answer_id": 366969, "author": "Kevin Marsden", "author_id": 19985, "author_profile": "https://wordpress.stackexchange.com/users/19985", "pm_score": 1, "selected": false, "text": "<p>The \"Now onwards\" string is translated with <a href=\"https://developer.wordpress.org/reference/functions/_x/\" rel=\"nofollow noreferrer\">_x()</a> which is different than __() because it allows context to be added to the string being translated. </p>\n\n<p>Because there is context, you need to use <a href=\"https://developer.wordpress.org/reference/hooks/gettext_with_context/\" rel=\"nofollow noreferrer\">gettext_with_context</a> instead of gettext. Here's a simple example based on the one in the WP.org Code Reference:</p>\n\n<pre><code>function example_gettext_with_context( $translated, $text ) {\n if ( 'Now' == $text ) {\n $translated = 'Today';\n }\n\n return $translated;\n}\nadd_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 2 );\n</code></pre>\n\n<p>You can find the relavent code in the Events Calendar plugin <a href=\"https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L49\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L158\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p><a href=\"https://theeventscalendar.com/knowledgebase/k/change-the-wording-of-any-bit-of-text-or-string/\" rel=\"nofollow noreferrer\">The Events Calendar website</a> also has some detailed examples. </p>\n" } ]
2020/02/22
[ "https://wordpress.stackexchange.com/questions/359286", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183185/" ]
I would like to remove the category title or tag from my individual posts on my archive pages. I have already succeeded in removing the tags from the homepage and archive page header but they still show up on the individual posts (they are in a red font). So the posts always have the category "Latest Post" next to the actual headline, for instance. I am using the Newsliner theme if that helps. Thanks
The "Now onwards" string is translated with [\_x()](https://developer.wordpress.org/reference/functions/_x/) which is different than \_\_() because it allows context to be added to the string being translated. Because there is context, you need to use [gettext\_with\_context](https://developer.wordpress.org/reference/hooks/gettext_with_context/) instead of gettext. Here's a simple example based on the one in the WP.org Code Reference: ``` function example_gettext_with_context( $translated, $text ) { if ( 'Now' == $text ) { $translated = 'Today'; } return $translated; } add_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 2 ); ``` You can find the relavent code in the Events Calendar plugin [here](https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L49) and [here](https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L158) [The Events Calendar website](https://theeventscalendar.com/knowledgebase/k/change-the-wording-of-any-bit-of-text-or-string/) also has some detailed examples.
359,291
<p>I am working on a small online shop and I am using Averta Phlox theme. As I encounter they have bug in a shopping cart. The cart do not work on mobile phones, as I can work a little fix for it using simple css and html, I am able to fix this bug. But I can't find the place for HTML part in this because it use aux design and elementor plugin. </p> <p>Maybe someone can suggest the place how to find the necessary part of the code. It is a Phlox cart widget what creates cart function in header file.</p> <p>My test site is here - <a href="https://eogame.eu/rietumi2/?post_type=product" rel="nofollow noreferrer">SHOP</a></p> <p>I would love to get some suggestion in this situation, because averta support are ignoring this issue for a 3 years. Thanks and sorry for bad English, it's not my native. </p>
[ { "answer_id": 359175, "author": "GarethTF", "author_id": 181549, "author_profile": "https://wordpress.stackexchange.com/users/181549", "pm_score": 0, "selected": false, "text": "<p>For only a couple of words I would use the gettext filter e.g.</p>\n\n<pre><code>function wse_text_filter( $translated_text, $untranslated_text ) {\n switch( $untranslated_text ) {\n\n case 'Now onwards':\n $translated_text = __( 'Now backwards','text_domain' );\n break;\n\n case 'onwards':\n $translated_text = __( 'Backwards','text_domain' );\n break;\n\n }\n return $translated_text;\n}\nadd_filter('gettext', 'wse_text_filter', 20, 3);\n</code></pre>\n\n<p>It's hopefully pretty self explanatory, you could also try language switching plugins such as Polyang or WPML.</p>\n" }, { "answer_id": 366969, "author": "Kevin Marsden", "author_id": 19985, "author_profile": "https://wordpress.stackexchange.com/users/19985", "pm_score": 1, "selected": false, "text": "<p>The \"Now onwards\" string is translated with <a href=\"https://developer.wordpress.org/reference/functions/_x/\" rel=\"nofollow noreferrer\">_x()</a> which is different than __() because it allows context to be added to the string being translated. </p>\n\n<p>Because there is context, you need to use <a href=\"https://developer.wordpress.org/reference/hooks/gettext_with_context/\" rel=\"nofollow noreferrer\">gettext_with_context</a> instead of gettext. Here's a simple example based on the one in the WP.org Code Reference:</p>\n\n<pre><code>function example_gettext_with_context( $translated, $text ) {\n if ( 'Now' == $text ) {\n $translated = 'Today';\n }\n\n return $translated;\n}\nadd_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 2 );\n</code></pre>\n\n<p>You can find the relavent code in the Events Calendar plugin <a href=\"https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L49\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L158\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p><a href=\"https://theeventscalendar.com/knowledgebase/k/change-the-wording-of-any-bit-of-text-or-string/\" rel=\"nofollow noreferrer\">The Events Calendar website</a> also has some detailed examples. </p>\n" } ]
2020/02/22
[ "https://wordpress.stackexchange.com/questions/359291", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183190/" ]
I am working on a small online shop and I am using Averta Phlox theme. As I encounter they have bug in a shopping cart. The cart do not work on mobile phones, as I can work a little fix for it using simple css and html, I am able to fix this bug. But I can't find the place for HTML part in this because it use aux design and elementor plugin. Maybe someone can suggest the place how to find the necessary part of the code. It is a Phlox cart widget what creates cart function in header file. My test site is here - [SHOP](https://eogame.eu/rietumi2/?post_type=product) I would love to get some suggestion in this situation, because averta support are ignoring this issue for a 3 years. Thanks and sorry for bad English, it's not my native.
The "Now onwards" string is translated with [\_x()](https://developer.wordpress.org/reference/functions/_x/) which is different than \_\_() because it allows context to be added to the string being translated. Because there is context, you need to use [gettext\_with\_context](https://developer.wordpress.org/reference/hooks/gettext_with_context/) instead of gettext. Here's a simple example based on the one in the WP.org Code Reference: ``` function example_gettext_with_context( $translated, $text ) { if ( 'Now' == $text ) { $translated = 'Today'; } return $translated; } add_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 2 ); ``` You can find the relavent code in the Events Calendar plugin [here](https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L49) and [here](https://plugins.trac.wordpress.org/browser/the-events-calendar/tags/5.1.1/src/Tribe/Views/V2/Views/Traits/List_Behavior.php#L158) [The Events Calendar website](https://theeventscalendar.com/knowledgebase/k/change-the-wording-of-any-bit-of-text-or-string/) also has some detailed examples.
359,313
<p>Wordpress compresses jpeg files to a lvl 82 quality. Should I upload my files in 100 quality to avoid double compression? Or will Wordpress know the file is already compressed and will skip this process?</p> <p>I usually save my files in photoshop in 80 quality , as progressive.</p> <p>Thank you</p>
[ { "answer_id": 359315, "author": "vbaimas", "author_id": 183044, "author_profile": "https://wordpress.stackexchange.com/users/183044", "pm_score": 1, "selected": false, "text": "<p>If you want to showcase high-quality images on your website, then you can turn off image compression in WordPress.</p>\n\n<p>You can do that by adding this part of code in your <code>functions.php</code> :</p>\n\n<p><code>add_filter('jpeg_quality', function($arg){return 100;});</code></p>\n\n<p>Or you can create your plugin :</p>\n\n<pre><code> &lt;?php \n /**\n * Plugin Name: Remove WordPress Image Compression\n * Plugin URI: [Plugun URI}\n * Version: 1.0\n * Author: [Your name]\n * Author URI: [Your URI]\n * Description: This will remove the compression WordPress, applies to images when uploading to your media library.\n */\n /**\n * Override the default image quality when resizing and cropping images\n */\n add_filter('jpeg_quality', function($arg){return 100;});\n</code></pre>\n\n<p>The code above sets the value to <strong>100</strong>. It means that WordPress compresses the image at its highest quality. </p>\n\n<p>Now, after activating the plugin, any new image uploaded will no longer be subject to WordPress image compression. Keep in mind that was previously uploaded to activating your plugin will need to be re-uploaded to have the compression removed.</p>\n" }, { "answer_id": 406039, "author": "Ben Rich", "author_id": 218932, "author_profile": "https://wordpress.stackexchange.com/users/218932", "pm_score": 1, "selected": false, "text": "<p>From looking at WordPress' sourcecode it appears to use the PHP function <a href=\"https://www.php.net/manual/en/function.imagejpeg.php\" rel=\"nofollow noreferrer\">imagejpeg</a> to save images. The PHP documentation doesn't mention anything about checking the quality before saving the image.</p>\n<p>So I did a test using <a href=\"https://stackoverflow.com/questions/2024947/is-it-possible-to-tell-the-quality-level-of-a-jpeg\">the identify tool in ImageMagick</a> and uploading images to WordPress.</p>\n<p>Image 1: 96% quality before upload &amp; 82% after upload (as expected)</p>\n<p>Image 2: 50% quality before upload &amp; 50% after upload.</p>\n<p>This admittedly naive test implies (to me at least) that image 2 was left untouched. If it had reduced the quality I'd expect something like 40% quality.</p>\n" }, { "answer_id": 406134, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 0, "selected": false, "text": "<p>Re-compressing a JPEG using the exact same settings does not result in quality loss beyond the initial compression. However, if the settings used by WordPress differ from those applied by your photo editing software, progressive degradation of the image may occur.</p>\n<p>The safest route to mitigate this potential degradation is indeed to upload your images at full quality.</p>\n<p>You could set the default quality level to match what you use in your photo editing software via the <a href=\"https://developer.wordpress.org/reference/hooks/jpeg_quality/\" rel=\"nofollow noreferrer\"><code>jpeg_quality</code> filter</a> - however, minor variations in the compression settings can still result in degradation. If you choose to go this route you might verify fidelity by checking a hash of the file output from your editing suite against that of the same image uploaded to WordPress.</p>\n<p>More on JPEG compression and degradation can be found <a href=\"https://photo.stackexchange.com/questions/99604/what-factors-cause-or-prevent-generational-loss-when-jpegs-are-recompressed-mu\">over on the Photography Stack</a>.</p>\n" } ]
2020/02/23
[ "https://wordpress.stackexchange.com/questions/359313", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71513/" ]
Wordpress compresses jpeg files to a lvl 82 quality. Should I upload my files in 100 quality to avoid double compression? Or will Wordpress know the file is already compressed and will skip this process? I usually save my files in photoshop in 80 quality , as progressive. Thank you
If you want to showcase high-quality images on your website, then you can turn off image compression in WordPress. You can do that by adding this part of code in your `functions.php` : `add_filter('jpeg_quality', function($arg){return 100;});` Or you can create your plugin : ``` <?php /** * Plugin Name: Remove WordPress Image Compression * Plugin URI: [Plugun URI} * Version: 1.0 * Author: [Your name] * Author URI: [Your URI] * Description: This will remove the compression WordPress, applies to images when uploading to your media library. */ /** * Override the default image quality when resizing and cropping images */ add_filter('jpeg_quality', function($arg){return 100;}); ``` The code above sets the value to **100**. It means that WordPress compresses the image at its highest quality. Now, after activating the plugin, any new image uploaded will no longer be subject to WordPress image compression. Keep in mind that was previously uploaded to activating your plugin will need to be re-uploaded to have the compression removed.
359,400
<p>I have some meta boxes setup, some are my own, some are initialized in plugins.</p> <p>As the title indicates, these meta boxes are not updating graphically after the post has been submitted.</p> <p>Here's an example of the problem, I have a metabox with a single toggle to enable notifications. After the first notification is sent and the post has been published, I unset the checkbox and add a little warning above it. However, this doesn't update until I refresh the page entirely.</p> <p>I'm fairly new to wordpress but this does not seem like the correct behaviour, as when I debug the code I can verify that the metabox callback is getting called after save_post.</p> <p>I can also see by viewing the Network tab in Chrome's Dev Tools, that when I 'save_post', it downloads a load of re-generated HTML with all the metaboxes updated. However I see no evidence of these elements updating in the editor.</p> <p>I suspect it might be due to a quirk in the new editor.</p> <p>It appears to be happening with all meta boxes, except funnily enough the featured image - I've got it set up so if there's no _thumbnail_id set then it sets one by default, and after saving the post this image appears in the featured image box.</p> <pre><code>function cabtv_add_post_options() { // Add our meta box for the "post" post type (default) if ( current_user_can("send_notifications") ) { $post_types = ["post", "go_live"]; foreach ($post_types as $post_type) { add_meta_box( 'cabtv_notif_on_post', 'Notifications', 'cabtv_notif_on_post_html_view', $post_type, 'side', 'high' ); } } } add_action('admin_init', 'cabtv_add_post_options'); function cabtv_notif_on_post_html_view($post) { //wp_nonce_field( 'cabtv_notif_metabox', 'cabtv_notif_metabox' ); $checked = cabtv_should_post_send_notification($post); if ( get_post_meta( $post-&gt;ID, 'cabtv_notifications_sent', true ) == "1" ) { ?&gt; &lt;div style='padding:10px;'&gt;&lt;span style='color:red; font-weight:bold;'&gt;Notifications have already been sent for this post.&lt;/span&gt;&lt;/div&gt; &lt;?php } ?&gt; &lt;input type="hidden" name="cabtv_meta_box_present" value="true"&gt;&lt;/input&gt; &lt;input type="checkbox" name="cabtv_send_notification" value="true" &lt;?php if ($checked) echo 'checked'; ?&gt;&gt;&lt;/input&gt; &lt;label&gt; &lt;?php echo esc_attr('Send notification on '.($post-&gt;post_status === 'publish' ? 'update' : 'publish') ); ?&gt; &lt;/label&gt; &lt;?php } </code></pre> <p>Some help would be appreciated.</p>
[ { "answer_id": 359403, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>I'd use a \"Search and Replace\" plugin (I like \"Better Search and Replace\") to search for all <a href=\"http://www.example.com\" rel=\"nofollow noreferrer\">http://www.example.com</a> and replace with <a href=\"https://www.example.com\" rel=\"nofollow noreferrer\">https://www.example.com</a> . That will fix media URLs, for instance, and other settings.</p>\n\n<p>It could also be that your theme is calling <code>http</code> resources rather than <code>https</code>. You could look in the Developer screen (F12 in your browser usually) at the Network tab to see what <code>http</code> (vs <code>https</code>) resources are being loaded, and use that info to find the source code that is using <code>http</code> instead of <code>https</code>.</p>\n\n<p>Backup your database first, of course, although I've had no problems with the \"Better Search and Replace\" plugin.</p>\n" }, { "answer_id": 359465, "author": "Giuseppe", "author_id": 183279, "author_profile": "https://wordpress.stackexchange.com/users/183279", "pm_score": 0, "selected": false, "text": "<p>Ok... I found this plug in\n<a href=\"https://wordpress.org/plugins/ssl-insecure-content-fixer/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/ssl-insecure-content-fixer/</a></p>\n\n<p>My site is also behind a load balance and this plugin solved everything.\nIt's running in real-time (I don't like that), but it keeps everything under control</p>\n" } ]
2020/02/24
[ "https://wordpress.stackexchange.com/questions/359400", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183281/" ]
I have some meta boxes setup, some are my own, some are initialized in plugins. As the title indicates, these meta boxes are not updating graphically after the post has been submitted. Here's an example of the problem, I have a metabox with a single toggle to enable notifications. After the first notification is sent and the post has been published, I unset the checkbox and add a little warning above it. However, this doesn't update until I refresh the page entirely. I'm fairly new to wordpress but this does not seem like the correct behaviour, as when I debug the code I can verify that the metabox callback is getting called after save\_post. I can also see by viewing the Network tab in Chrome's Dev Tools, that when I 'save\_post', it downloads a load of re-generated HTML with all the metaboxes updated. However I see no evidence of these elements updating in the editor. I suspect it might be due to a quirk in the new editor. It appears to be happening with all meta boxes, except funnily enough the featured image - I've got it set up so if there's no \_thumbnail\_id set then it sets one by default, and after saving the post this image appears in the featured image box. ``` function cabtv_add_post_options() { // Add our meta box for the "post" post type (default) if ( current_user_can("send_notifications") ) { $post_types = ["post", "go_live"]; foreach ($post_types as $post_type) { add_meta_box( 'cabtv_notif_on_post', 'Notifications', 'cabtv_notif_on_post_html_view', $post_type, 'side', 'high' ); } } } add_action('admin_init', 'cabtv_add_post_options'); function cabtv_notif_on_post_html_view($post) { //wp_nonce_field( 'cabtv_notif_metabox', 'cabtv_notif_metabox' ); $checked = cabtv_should_post_send_notification($post); if ( get_post_meta( $post->ID, 'cabtv_notifications_sent', true ) == "1" ) { ?> <div style='padding:10px;'><span style='color:red; font-weight:bold;'>Notifications have already been sent for this post.</span></div> <?php } ?> <input type="hidden" name="cabtv_meta_box_present" value="true"></input> <input type="checkbox" name="cabtv_send_notification" value="true" <?php if ($checked) echo 'checked'; ?>></input> <label> <?php echo esc_attr('Send notification on '.($post->post_status === 'publish' ? 'update' : 'publish') ); ?> </label> <?php } ``` Some help would be appreciated.
I'd use a "Search and Replace" plugin (I like "Better Search and Replace") to search for all <http://www.example.com> and replace with <https://www.example.com> . That will fix media URLs, for instance, and other settings. It could also be that your theme is calling `http` resources rather than `https`. You could look in the Developer screen (F12 in your browser usually) at the Network tab to see what `http` (vs `https`) resources are being loaded, and use that info to find the source code that is using `http` instead of `https`. Backup your database first, of course, although I've had no problems with the "Better Search and Replace" plugin.
359,541
<p>I am initializing a class where the constructor requires a WP_Post object. The object I would like to pass comes from <code>get_queried_object()</code> which could return almost anything. I am using <code>is_a()</code> to make sure I have the right type, which "works", but my IDE does not recognize that I have constrained the type.</p> <p>Is there a way to make it clear to the IDE that I have done my due diligence? I don't want to get in the habit of ignoring my IDE. It has been so nice to me in the past and saved me from so many mistakes. :)</p> <pre><code>$queried_object = get_queried_object(); if ( is_singular() &amp;&amp; is_a( $queried_object, 'WP_Post' ) ) { // Initialize class that requires WP_Post object. $class = new ClassThatOnlyAcceptsPostObject( $queried_object ); // ... } </code></pre>
[ { "answer_id": 359403, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>I'd use a \"Search and Replace\" plugin (I like \"Better Search and Replace\") to search for all <a href=\"http://www.example.com\" rel=\"nofollow noreferrer\">http://www.example.com</a> and replace with <a href=\"https://www.example.com\" rel=\"nofollow noreferrer\">https://www.example.com</a> . That will fix media URLs, for instance, and other settings.</p>\n\n<p>It could also be that your theme is calling <code>http</code> resources rather than <code>https</code>. You could look in the Developer screen (F12 in your browser usually) at the Network tab to see what <code>http</code> (vs <code>https</code>) resources are being loaded, and use that info to find the source code that is using <code>http</code> instead of <code>https</code>.</p>\n\n<p>Backup your database first, of course, although I've had no problems with the \"Better Search and Replace\" plugin.</p>\n" }, { "answer_id": 359465, "author": "Giuseppe", "author_id": 183279, "author_profile": "https://wordpress.stackexchange.com/users/183279", "pm_score": 0, "selected": false, "text": "<p>Ok... I found this plug in\n<a href=\"https://wordpress.org/plugins/ssl-insecure-content-fixer/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/ssl-insecure-content-fixer/</a></p>\n\n<p>My site is also behind a load balance and this plugin solved everything.\nIt's running in real-time (I don't like that), but it keeps everything under control</p>\n" } ]
2020/02/26
[ "https://wordpress.stackexchange.com/questions/359541", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/11310/" ]
I am initializing a class where the constructor requires a WP\_Post object. The object I would like to pass comes from `get_queried_object()` which could return almost anything. I am using `is_a()` to make sure I have the right type, which "works", but my IDE does not recognize that I have constrained the type. Is there a way to make it clear to the IDE that I have done my due diligence? I don't want to get in the habit of ignoring my IDE. It has been so nice to me in the past and saved me from so many mistakes. :) ``` $queried_object = get_queried_object(); if ( is_singular() && is_a( $queried_object, 'WP_Post' ) ) { // Initialize class that requires WP_Post object. $class = new ClassThatOnlyAcceptsPostObject( $queried_object ); // ... } ```
I'd use a "Search and Replace" plugin (I like "Better Search and Replace") to search for all <http://www.example.com> and replace with <https://www.example.com> . That will fix media URLs, for instance, and other settings. It could also be that your theme is calling `http` resources rather than `https`. You could look in the Developer screen (F12 in your browser usually) at the Network tab to see what `http` (vs `https`) resources are being loaded, and use that info to find the source code that is using `http` instead of `https`. Backup your database first, of course, although I've had no problems with the "Better Search and Replace" plugin.
359,560
<p>am trying to crop my thumbnail in my loop, am having some problems when i crop using codes some images appear either big in width or height here is my code Css</p> <pre><code>.imgholder {float:left;margin-right:20px; margin-left:20px;height:240px;width:240px;} </code></pre> <p>loop</p> <pre><code>&lt;?php the_post_thumbnail( 'large' , array('class' =&gt; 'imgholder')); ?&gt; </code></pre> <p>when i change the 'large' to 'thumbnail' from the above it works perfectly please help Thank you</p>
[ { "answer_id": 359403, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>I'd use a \"Search and Replace\" plugin (I like \"Better Search and Replace\") to search for all <a href=\"http://www.example.com\" rel=\"nofollow noreferrer\">http://www.example.com</a> and replace with <a href=\"https://www.example.com\" rel=\"nofollow noreferrer\">https://www.example.com</a> . That will fix media URLs, for instance, and other settings.</p>\n\n<p>It could also be that your theme is calling <code>http</code> resources rather than <code>https</code>. You could look in the Developer screen (F12 in your browser usually) at the Network tab to see what <code>http</code> (vs <code>https</code>) resources are being loaded, and use that info to find the source code that is using <code>http</code> instead of <code>https</code>.</p>\n\n<p>Backup your database first, of course, although I've had no problems with the \"Better Search and Replace\" plugin.</p>\n" }, { "answer_id": 359465, "author": "Giuseppe", "author_id": 183279, "author_profile": "https://wordpress.stackexchange.com/users/183279", "pm_score": 0, "selected": false, "text": "<p>Ok... I found this plug in\n<a href=\"https://wordpress.org/plugins/ssl-insecure-content-fixer/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/ssl-insecure-content-fixer/</a></p>\n\n<p>My site is also behind a load balance and this plugin solved everything.\nIt's running in real-time (I don't like that), but it keeps everything under control</p>\n" } ]
2020/02/26
[ "https://wordpress.stackexchange.com/questions/359560", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183184/" ]
am trying to crop my thumbnail in my loop, am having some problems when i crop using codes some images appear either big in width or height here is my code Css ``` .imgholder {float:left;margin-right:20px; margin-left:20px;height:240px;width:240px;} ``` loop ``` <?php the_post_thumbnail( 'large' , array('class' => 'imgholder')); ?> ``` when i change the 'large' to 'thumbnail' from the above it works perfectly please help Thank you
I'd use a "Search and Replace" plugin (I like "Better Search and Replace") to search for all <http://www.example.com> and replace with <https://www.example.com> . That will fix media URLs, for instance, and other settings. It could also be that your theme is calling `http` resources rather than `https`. You could look in the Developer screen (F12 in your browser usually) at the Network tab to see what `http` (vs `https`) resources are being loaded, and use that info to find the source code that is using `http` instead of `https`. Backup your database first, of course, although I've had no problems with the "Better Search and Replace" plugin.
359,597
<p>I'm trying to use this simple code to insert page (1) content into another page (2): </p> <pre><code> &lt;?php $id = 216; $p = get_page($id); echo apply_filters('the_content', $p-&gt;post_content); ?&gt; </code></pre> <p>So far so good. The inserted page (1), though, is some html code that at one point contains </p> <pre><code>value="&lt;?php echo $url?&gt;" </code></pre> <p>Is there any way I can edit the value of that variable in the code above, i.e. in page (2)? </p> <p>Thank you!</p>
[ { "answer_id": 359611, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 0, "selected": false, "text": "<p>There's a fundamental problem in your code, and one that suggests you're doing something very dangerous in your code.</p>\n\n<p>Given this code:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$id = 216;\n$p = get_page($id);\necho apply_filters('the_content', $p-&gt;post_content);\n</code></pre>\n\n<p>I would expect this to be running from a template file, however, the question claims that the post content contains this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>value=\"&lt;?php echo $url?&gt;\"\n</code></pre>\n\n<p>This is not possible in normal WordPress, so you must be using a plugin that lets you put PHP tags inside post content. This is the source of all your problems. Because of this:</p>\n\n<ul>\n<li>Most WordPress knowledge is unusable to you</li>\n<li>The vast majority of tutorials will not work as they assume you're in a template file</li>\n<li>Large numbers of solutions simply won't work correctly</li>\n</ul>\n\n<p>Using plugins that let you embed PHP inside a post is extremely unusual, and super important to know. A person unaware of this will suggest things that will not work.</p>\n\n<p>This is one of those situations where the answer you seek is not possible using a plugin that lets you use PHP inside a posts content.</p>\n\n<p>Additionally, it's incredibly dangerous from a security point of view. <strong>But there is a much easier way that uses standard WordPress practices</strong></p>\n\n<p>Thus, I do not believe it is possible to solve your problem as long as you persist with the plugin allowing you to embed PHP inside a post. Never use something that lets you store PHP code in the database and run it from the database.</p>\n\n<h3>Shortcodes</h3>\n\n<p>If you need to embed PHP logic inside a post/page, create a shortcode.</p>\n\n<p>This way, your page can be something like this:</p>\n\n<blockquote>\n <p>My page!</p>\n \n <p>[kristynas_form foo=\"bar\"]</p>\n</blockquote>\n\n<p>In a plugin or your themes <code>functions.php</code> you can use something like this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_shortcode( 'kristynas_form', function( array $attributes ) {\n $foo = $attributes['bar'];\n return 'form HTML';\n});\n</code></pre>\n\n<p>When the page gets rendered the shortcode gets swapped out. This is how you're supposed to implement things like iframes, forms, and other complex logic that appears inline.</p>\n" }, { "answer_id": 359734, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 1, "selected": false, "text": "<p>Assuming you want to replace it with some static value (well, you can always change this anyway), some kind of find and replace snippet like this can do the trick:</p>\n\n<pre><code>$content = apply_filters( 'the_content', $post-&gt;post_content);\n// set the replacement string value\n$replace = \"REPLACEMENT\";\n// make sure the quotes used are exact\n$find_start = \"&lt;param name='filter' \" . 'value=\"';\n$find_end = '\"';\n// find the (end of) search string start position\n$pos = strpos( $content, $find_start) + strlen( $find_start );\n// get the content before (end of) search string\n$before = substr( $content, 0, $pos );\n// get content after search string\n$after = substr( $content, $pos, strlen( $content ) );\n// strip the after-content before end quote\n$pos2 = strpos( $after, $find_end );\n$after = substr( $after, $pos2, strlen( $after) );\n// recombine content with replacement value\n$content = $before . $replace . $after );\nreturn $content;\n</code></pre>\n" } ]
2020/02/27
[ "https://wordpress.stackexchange.com/questions/359597", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183438/" ]
I'm trying to use this simple code to insert page (1) content into another page (2): ``` <?php $id = 216; $p = get_page($id); echo apply_filters('the_content', $p->post_content); ?> ``` So far so good. The inserted page (1), though, is some html code that at one point contains ``` value="<?php echo $url?>" ``` Is there any way I can edit the value of that variable in the code above, i.e. in page (2)? Thank you!
Assuming you want to replace it with some static value (well, you can always change this anyway), some kind of find and replace snippet like this can do the trick: ``` $content = apply_filters( 'the_content', $post->post_content); // set the replacement string value $replace = "REPLACEMENT"; // make sure the quotes used are exact $find_start = "<param name='filter' " . 'value="'; $find_end = '"'; // find the (end of) search string start position $pos = strpos( $content, $find_start) + strlen( $find_start ); // get the content before (end of) search string $before = substr( $content, 0, $pos ); // get content after search string $after = substr( $content, $pos, strlen( $content ) ); // strip the after-content before end quote $pos2 = strpos( $after, $find_end ); $after = substr( $after, $pos2, strlen( $after) ); // recombine content with replacement value $content = $before . $replace . $after ); return $content; ```
359,599
<p>I am using this code in my plugin to enqueue script:</p> <pre><code>wp_enqueue_script( 'wpfrank-ptbw-pinit-js', PTBW_PLUGIN_URL . 'assets/js/pinit.js', array('jquery'), '', true ); </code></pre> <p>The <code>wp_enqueue_script</code> function making a default <code>&lt;script&gt;</code> tag output like this:</p> <pre><code>&lt;script type='text/javascript' src='http://localhost/development/wp-content/plugins/pin-it-button-pinterest-widgets/assets/js/pinit.js'&gt;&lt;/script&gt; </code></pre> <p>Want to add some extra parameter into the script tags like:</p> <pre><code>&lt;script async defer data-pin-hover="true" src="http://localhost/development/wp-content/plugins/pin-it-button-pinterest-widgets/assets/js/pinit.js"&gt;&lt;/script&gt; </code></pre> <ol> <li><code>asysnc</code> </li> <li><code>defer</code></li> <li><code>data-pinhover="true"</code></li> </ol> <p>How do I achieve that using <a href="https://developer.wordpress.org/reference/functions/wp_enqueue_script/" rel="nofollow noreferrer">wp_enqueue_script</a>?</p> <p>Are there any hook or action to pass extra parameters?</p> <p>Any help really appreciated.</p>
[ { "answer_id": 359606, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": false, "text": "<p>I revised the answer once more because I recently noticed how the <a href=\"https://wordpress.org/themes/twentytwenty/\" rel=\"nofollow noreferrer\">Twenty Twenty</a> developers use the <code>script_loader_tag</code> hook to add <code>async</code> and <code>defer</code> to the <code>&lt;script&gt;</code> tag for the theme scripts.</p>\n\n<ol>\n<li><p>In <code>twentytwenty_theme_support()</code> in <code>functions.php</code>, <a href=\"https://themes.trac.wordpress.org/browser/twentytwenty/1.1/functions.php#L139\" rel=\"nofollow noreferrer\">lines #139 &amp; #140</a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$loader = new TwentyTwenty_Script_Loader();\nadd_filter( 'script_loader_tag', array( $loader, 'filter_script_loader_tag' ), 10, 2 );\n</code></pre></li>\n<li><p>In <code>twentytwenty_register_scripts()</code> in <code>functions.php</code>, <a href=\"https://themes.trac.wordpress.org/browser/twentytwenty/1.1/functions.php#L208\" rel=\"nofollow noreferrer\">lines #208 &amp; #209</a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>wp_enqueue_script( 'twentytwenty-js', get_template_directory_uri() . '/assets/js/index.js', array(), $theme_version, false );\nwp_script_add_data( 'twentytwenty-js', 'async', true );\n</code></pre></li>\n<li><p>And in the <a href=\"https://themes.trac.wordpress.org/browser/twentytwenty/1.1/classes/class-twentytwenty-script-loader.php\" rel=\"nofollow noreferrer\"><code>TwentyTwenty_Script_Loader</code> class</a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>public function filter_script_loader_tag( $tag, $handle ) {\n foreach ( [ 'async', 'defer' ] as $attr ) {\n if ( ! wp_scripts()-&gt;get_data( $handle, $attr ) ) {\n continue;\n }\n ...\n }\n return $tag;\n}\n</code></pre></li>\n</ol>\n\n<p>So what I'm trying to say/suggest, is that you should probably better off use the <a href=\"https://developer.wordpress.org/reference/functions/wp_script_add_data/\" rel=\"nofollow noreferrer\"><code>wp_script_add_data()</code></a> to add/register the custom HTML attributes (e.g. <code>async</code>) for your scripts and use the <code>wp_scripts()-&gt;get_data()</code> to check if the <code>&lt;script&gt;</code> tag should be added with the custom HTML attributes, without having to manually specify the handle (e.g. your <code>wpfrank-ptbw-pinit-js</code>).</p>\n\n<p>And here's an example based on the above approach, where I'm registering a list of custom or extra HTML attributes for a script using <code>wp_script_add_data( '&lt;handle&gt;', 'html_attrs', [ list here ] )</code>. Additionally, I'm using PHP's <a href=\"https://www.php.net/manual/en/class.domdocument.php\" rel=\"nofollow noreferrer\"><code>DOMDocument</code></a> for a more precise result, although <code>str_replace()</code> or <code>preg_replace()</code> would also do.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'wp_enqueue_scripts', 'my_register_scripts' );\nfunction my_register_scripts() {\n wp_enqueue_script( 'wpfrank-ptbw-pinit-js', PTBW_PLUGIN_URL . 'assets/js/pinit.js', array( 'jquery' ), '', true );\n wp_script_add_data( 'wpfrank-ptbw-pinit-js', 'html_attrs', [\n 'async' =&gt; 'async',\n 'defer' =&gt; true,\n 'data-pin-hover' =&gt; 'true',\n ] );\n}\n\nadd_filter( 'script_loader_tag', 'my_filter_script_loader_tag', 10, 2 );\nfunction my_filter_script_loader_tag( $tag, $handle ) {\n $attrs = wp_scripts()-&gt;get_data( $handle, 'html_attrs' );\n\n // Bail if the script doesn't have any registered custom HTML attrs.\n if ( empty( $attrs ) || ! is_array( $attrs ) ) {\n return $tag;\n }\n\n $dom = new DOMDocument;\n\n //$tag = mb_convert_encoding( $tag, 'HTML-ENTITIES', 'UTF-8' );\n $dom-&gt;loadHTML( $tag, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );\n\n $node = $dom-&gt;getElementsByTagName( 'script' )[0];\n foreach ( $attrs as $key =&gt; $value ) {\n $node-&gt;setAttribute( $key, $value );\n }\n\n return $dom-&gt;saveHTML();\n}\n</code></pre>\n" }, { "answer_id": 359607, "author": "Chetan Vaghela", "author_id": 169856, "author_profile": "https://wordpress.stackexchange.com/users/169856", "pm_score": 3, "selected": false, "text": "<p>You can use <code>script_loader_tag</code> filter to fulfill your requirement. add below code in your active theme's functions.php file. it will add extra parameter in your script tag.</p>\n\n<pre><code>function add_attribute_to_script_tag($tag, $handle) {\n # add script handles to the array below\n $scripts_to_defer = array('wpfrank-ptbw-pinit-js');\n\n foreach($scripts_to_defer as $defer_script) {\n if ($defer_script === $handle) {\n return str_replace(' src', ' async defer data-pin-hover=\"true\" src', $tag);\n }\n }\n return $tag;\n}\nadd_filter('script_loader_tag', 'add_attribute_to_script_tag', 10, 2);\n</code></pre>\n" }, { "answer_id": 365734, "author": "José Carlos", "author_id": 187368, "author_profile": "https://wordpress.stackexchange.com/users/187368", "pm_score": 1, "selected": false, "text": "<p>In addition of Chetan Vaghela answer, you can use a switch statement, only for performance and customization related purposes:</p>\n\n<pre><code>function add_attribute_to_script_tag($tag, $handle) {\n\n switch($handle){\n case 'wpfrank-ptbw-pinit-js': return str_replace(' src', ' async defer data-pin-hover=\"true\" src', $tag);\n default: return $tag;\n }\n}\nadd_filter('script_loader_tag', 'add_attribute_to_script_tag', 10, 2);\n</code></pre>\n" } ]
2020/02/27
[ "https://wordpress.stackexchange.com/questions/359599", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25262/" ]
I am using this code in my plugin to enqueue script: ``` wp_enqueue_script( 'wpfrank-ptbw-pinit-js', PTBW_PLUGIN_URL . 'assets/js/pinit.js', array('jquery'), '', true ); ``` The `wp_enqueue_script` function making a default `<script>` tag output like this: ``` <script type='text/javascript' src='http://localhost/development/wp-content/plugins/pin-it-button-pinterest-widgets/assets/js/pinit.js'></script> ``` Want to add some extra parameter into the script tags like: ``` <script async defer data-pin-hover="true" src="http://localhost/development/wp-content/plugins/pin-it-button-pinterest-widgets/assets/js/pinit.js"></script> ``` 1. `asysnc` 2. `defer` 3. `data-pinhover="true"` How do I achieve that using [wp\_enqueue\_script](https://developer.wordpress.org/reference/functions/wp_enqueue_script/)? Are there any hook or action to pass extra parameters? Any help really appreciated.
I revised the answer once more because I recently noticed how the [Twenty Twenty](https://wordpress.org/themes/twentytwenty/) developers use the `script_loader_tag` hook to add `async` and `defer` to the `<script>` tag for the theme scripts. 1. In `twentytwenty_theme_support()` in `functions.php`, [lines #139 & #140](https://themes.trac.wordpress.org/browser/twentytwenty/1.1/functions.php#L139): ```php $loader = new TwentyTwenty_Script_Loader(); add_filter( 'script_loader_tag', array( $loader, 'filter_script_loader_tag' ), 10, 2 ); ``` 2. In `twentytwenty_register_scripts()` in `functions.php`, [lines #208 & #209](https://themes.trac.wordpress.org/browser/twentytwenty/1.1/functions.php#L208): ```php wp_enqueue_script( 'twentytwenty-js', get_template_directory_uri() . '/assets/js/index.js', array(), $theme_version, false ); wp_script_add_data( 'twentytwenty-js', 'async', true ); ``` 3. And in the [`TwentyTwenty_Script_Loader` class](https://themes.trac.wordpress.org/browser/twentytwenty/1.1/classes/class-twentytwenty-script-loader.php): ```php public function filter_script_loader_tag( $tag, $handle ) { foreach ( [ 'async', 'defer' ] as $attr ) { if ( ! wp_scripts()->get_data( $handle, $attr ) ) { continue; } ... } return $tag; } ``` So what I'm trying to say/suggest, is that you should probably better off use the [`wp_script_add_data()`](https://developer.wordpress.org/reference/functions/wp_script_add_data/) to add/register the custom HTML attributes (e.g. `async`) for your scripts and use the `wp_scripts()->get_data()` to check if the `<script>` tag should be added with the custom HTML attributes, without having to manually specify the handle (e.g. your `wpfrank-ptbw-pinit-js`). And here's an example based on the above approach, where I'm registering a list of custom or extra HTML attributes for a script using `wp_script_add_data( '<handle>', 'html_attrs', [ list here ] )`. Additionally, I'm using PHP's [`DOMDocument`](https://www.php.net/manual/en/class.domdocument.php) for a more precise result, although `str_replace()` or `preg_replace()` would also do. ```php add_action( 'wp_enqueue_scripts', 'my_register_scripts' ); function my_register_scripts() { wp_enqueue_script( 'wpfrank-ptbw-pinit-js', PTBW_PLUGIN_URL . 'assets/js/pinit.js', array( 'jquery' ), '', true ); wp_script_add_data( 'wpfrank-ptbw-pinit-js', 'html_attrs', [ 'async' => 'async', 'defer' => true, 'data-pin-hover' => 'true', ] ); } add_filter( 'script_loader_tag', 'my_filter_script_loader_tag', 10, 2 ); function my_filter_script_loader_tag( $tag, $handle ) { $attrs = wp_scripts()->get_data( $handle, 'html_attrs' ); // Bail if the script doesn't have any registered custom HTML attrs. if ( empty( $attrs ) || ! is_array( $attrs ) ) { return $tag; } $dom = new DOMDocument; //$tag = mb_convert_encoding( $tag, 'HTML-ENTITIES', 'UTF-8' ); $dom->loadHTML( $tag, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD ); $node = $dom->getElementsByTagName( 'script' )[0]; foreach ( $attrs as $key => $value ) { $node->setAttribute( $key, $value ); } return $dom->saveHTML(); } ```
359,632
<p>Within the network admin, the <strong>My Sites</strong> link, is not linking to the main parent site. Instead, it links to a child site blog. How can I change this link? Is there a way to rebuild WP menu? I haven't a clue how it became the wrong link.</p> <p><a href="https://i.stack.imgur.com/11kFS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/11kFS.png" alt="enter image description here"></a></p>
[ { "answer_id": 359606, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": false, "text": "<p>I revised the answer once more because I recently noticed how the <a href=\"https://wordpress.org/themes/twentytwenty/\" rel=\"nofollow noreferrer\">Twenty Twenty</a> developers use the <code>script_loader_tag</code> hook to add <code>async</code> and <code>defer</code> to the <code>&lt;script&gt;</code> tag for the theme scripts.</p>\n\n<ol>\n<li><p>In <code>twentytwenty_theme_support()</code> in <code>functions.php</code>, <a href=\"https://themes.trac.wordpress.org/browser/twentytwenty/1.1/functions.php#L139\" rel=\"nofollow noreferrer\">lines #139 &amp; #140</a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$loader = new TwentyTwenty_Script_Loader();\nadd_filter( 'script_loader_tag', array( $loader, 'filter_script_loader_tag' ), 10, 2 );\n</code></pre></li>\n<li><p>In <code>twentytwenty_register_scripts()</code> in <code>functions.php</code>, <a href=\"https://themes.trac.wordpress.org/browser/twentytwenty/1.1/functions.php#L208\" rel=\"nofollow noreferrer\">lines #208 &amp; #209</a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>wp_enqueue_script( 'twentytwenty-js', get_template_directory_uri() . '/assets/js/index.js', array(), $theme_version, false );\nwp_script_add_data( 'twentytwenty-js', 'async', true );\n</code></pre></li>\n<li><p>And in the <a href=\"https://themes.trac.wordpress.org/browser/twentytwenty/1.1/classes/class-twentytwenty-script-loader.php\" rel=\"nofollow noreferrer\"><code>TwentyTwenty_Script_Loader</code> class</a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>public function filter_script_loader_tag( $tag, $handle ) {\n foreach ( [ 'async', 'defer' ] as $attr ) {\n if ( ! wp_scripts()-&gt;get_data( $handle, $attr ) ) {\n continue;\n }\n ...\n }\n return $tag;\n}\n</code></pre></li>\n</ol>\n\n<p>So what I'm trying to say/suggest, is that you should probably better off use the <a href=\"https://developer.wordpress.org/reference/functions/wp_script_add_data/\" rel=\"nofollow noreferrer\"><code>wp_script_add_data()</code></a> to add/register the custom HTML attributes (e.g. <code>async</code>) for your scripts and use the <code>wp_scripts()-&gt;get_data()</code> to check if the <code>&lt;script&gt;</code> tag should be added with the custom HTML attributes, without having to manually specify the handle (e.g. your <code>wpfrank-ptbw-pinit-js</code>).</p>\n\n<p>And here's an example based on the above approach, where I'm registering a list of custom or extra HTML attributes for a script using <code>wp_script_add_data( '&lt;handle&gt;', 'html_attrs', [ list here ] )</code>. Additionally, I'm using PHP's <a href=\"https://www.php.net/manual/en/class.domdocument.php\" rel=\"nofollow noreferrer\"><code>DOMDocument</code></a> for a more precise result, although <code>str_replace()</code> or <code>preg_replace()</code> would also do.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'wp_enqueue_scripts', 'my_register_scripts' );\nfunction my_register_scripts() {\n wp_enqueue_script( 'wpfrank-ptbw-pinit-js', PTBW_PLUGIN_URL . 'assets/js/pinit.js', array( 'jquery' ), '', true );\n wp_script_add_data( 'wpfrank-ptbw-pinit-js', 'html_attrs', [\n 'async' =&gt; 'async',\n 'defer' =&gt; true,\n 'data-pin-hover' =&gt; 'true',\n ] );\n}\n\nadd_filter( 'script_loader_tag', 'my_filter_script_loader_tag', 10, 2 );\nfunction my_filter_script_loader_tag( $tag, $handle ) {\n $attrs = wp_scripts()-&gt;get_data( $handle, 'html_attrs' );\n\n // Bail if the script doesn't have any registered custom HTML attrs.\n if ( empty( $attrs ) || ! is_array( $attrs ) ) {\n return $tag;\n }\n\n $dom = new DOMDocument;\n\n //$tag = mb_convert_encoding( $tag, 'HTML-ENTITIES', 'UTF-8' );\n $dom-&gt;loadHTML( $tag, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );\n\n $node = $dom-&gt;getElementsByTagName( 'script' )[0];\n foreach ( $attrs as $key =&gt; $value ) {\n $node-&gt;setAttribute( $key, $value );\n }\n\n return $dom-&gt;saveHTML();\n}\n</code></pre>\n" }, { "answer_id": 359607, "author": "Chetan Vaghela", "author_id": 169856, "author_profile": "https://wordpress.stackexchange.com/users/169856", "pm_score": 3, "selected": false, "text": "<p>You can use <code>script_loader_tag</code> filter to fulfill your requirement. add below code in your active theme's functions.php file. it will add extra parameter in your script tag.</p>\n\n<pre><code>function add_attribute_to_script_tag($tag, $handle) {\n # add script handles to the array below\n $scripts_to_defer = array('wpfrank-ptbw-pinit-js');\n\n foreach($scripts_to_defer as $defer_script) {\n if ($defer_script === $handle) {\n return str_replace(' src', ' async defer data-pin-hover=\"true\" src', $tag);\n }\n }\n return $tag;\n}\nadd_filter('script_loader_tag', 'add_attribute_to_script_tag', 10, 2);\n</code></pre>\n" }, { "answer_id": 365734, "author": "José Carlos", "author_id": 187368, "author_profile": "https://wordpress.stackexchange.com/users/187368", "pm_score": 1, "selected": false, "text": "<p>In addition of Chetan Vaghela answer, you can use a switch statement, only for performance and customization related purposes:</p>\n\n<pre><code>function add_attribute_to_script_tag($tag, $handle) {\n\n switch($handle){\n case 'wpfrank-ptbw-pinit-js': return str_replace(' src', ' async defer data-pin-hover=\"true\" src', $tag);\n default: return $tag;\n }\n}\nadd_filter('script_loader_tag', 'add_attribute_to_script_tag', 10, 2);\n</code></pre>\n" } ]
2020/02/27
[ "https://wordpress.stackexchange.com/questions/359632", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/181079/" ]
Within the network admin, the **My Sites** link, is not linking to the main parent site. Instead, it links to a child site blog. How can I change this link? Is there a way to rebuild WP menu? I haven't a clue how it became the wrong link. [![enter image description here](https://i.stack.imgur.com/11kFS.png)](https://i.stack.imgur.com/11kFS.png)
I revised the answer once more because I recently noticed how the [Twenty Twenty](https://wordpress.org/themes/twentytwenty/) developers use the `script_loader_tag` hook to add `async` and `defer` to the `<script>` tag for the theme scripts. 1. In `twentytwenty_theme_support()` in `functions.php`, [lines #139 & #140](https://themes.trac.wordpress.org/browser/twentytwenty/1.1/functions.php#L139): ```php $loader = new TwentyTwenty_Script_Loader(); add_filter( 'script_loader_tag', array( $loader, 'filter_script_loader_tag' ), 10, 2 ); ``` 2. In `twentytwenty_register_scripts()` in `functions.php`, [lines #208 & #209](https://themes.trac.wordpress.org/browser/twentytwenty/1.1/functions.php#L208): ```php wp_enqueue_script( 'twentytwenty-js', get_template_directory_uri() . '/assets/js/index.js', array(), $theme_version, false ); wp_script_add_data( 'twentytwenty-js', 'async', true ); ``` 3. And in the [`TwentyTwenty_Script_Loader` class](https://themes.trac.wordpress.org/browser/twentytwenty/1.1/classes/class-twentytwenty-script-loader.php): ```php public function filter_script_loader_tag( $tag, $handle ) { foreach ( [ 'async', 'defer' ] as $attr ) { if ( ! wp_scripts()->get_data( $handle, $attr ) ) { continue; } ... } return $tag; } ``` So what I'm trying to say/suggest, is that you should probably better off use the [`wp_script_add_data()`](https://developer.wordpress.org/reference/functions/wp_script_add_data/) to add/register the custom HTML attributes (e.g. `async`) for your scripts and use the `wp_scripts()->get_data()` to check if the `<script>` tag should be added with the custom HTML attributes, without having to manually specify the handle (e.g. your `wpfrank-ptbw-pinit-js`). And here's an example based on the above approach, where I'm registering a list of custom or extra HTML attributes for a script using `wp_script_add_data( '<handle>', 'html_attrs', [ list here ] )`. Additionally, I'm using PHP's [`DOMDocument`](https://www.php.net/manual/en/class.domdocument.php) for a more precise result, although `str_replace()` or `preg_replace()` would also do. ```php add_action( 'wp_enqueue_scripts', 'my_register_scripts' ); function my_register_scripts() { wp_enqueue_script( 'wpfrank-ptbw-pinit-js', PTBW_PLUGIN_URL . 'assets/js/pinit.js', array( 'jquery' ), '', true ); wp_script_add_data( 'wpfrank-ptbw-pinit-js', 'html_attrs', [ 'async' => 'async', 'defer' => true, 'data-pin-hover' => 'true', ] ); } add_filter( 'script_loader_tag', 'my_filter_script_loader_tag', 10, 2 ); function my_filter_script_loader_tag( $tag, $handle ) { $attrs = wp_scripts()->get_data( $handle, 'html_attrs' ); // Bail if the script doesn't have any registered custom HTML attrs. if ( empty( $attrs ) || ! is_array( $attrs ) ) { return $tag; } $dom = new DOMDocument; //$tag = mb_convert_encoding( $tag, 'HTML-ENTITIES', 'UTF-8' ); $dom->loadHTML( $tag, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD ); $node = $dom->getElementsByTagName( 'script' )[0]; foreach ( $attrs as $key => $value ) { $node->setAttribute( $key, $value ); } return $dom->saveHTML(); } ```
359,660
<p>I've created a quick function and shortcode to allow me to include logged-in user only content:</p> <pre><code>function content_for_logged_in($atts,$content){ $logged_in_content = ""; if(is_user_logged_in()){ $logged_in_content = $content; } return $logged_in_content; } add_shortcode('logged-in-content','content_for_logged_in'); </code></pre> <p>But it doesn't parse shortcodes that are within the content, e.g.:</p> <pre><code>[logged-in-content] &lt;p&gt;Some test content...&lt;/p&gt; [wpforms id="752"] [/logged-in-content] </code></pre> <p>...in this case, the wpforms shortcode is displayed rather than the form.</p> <p>Is there a way to alter my function so that shortcodes within the content will be parsed?</p> <p>Thanks, Scott</p>
[ { "answer_id": 359661, "author": "ScottM", "author_id": 57399, "author_profile": "https://wordpress.stackexchange.com/users/57399", "pm_score": 0, "selected": false, "text": "<p>I found a way to achieve what I need right now...</p>\n\n<pre><code> function content_for_logged_in($atts,$content){\n $logged_in_content = \"\";\n $embedded_shortcode = $atts['embedded_shortcode'];\n if(is_user_logged_in()){\n $logged_in_content = $content;\n if(!empty($embedded_shortcode)) {\n $logged_in_content .= do_shortcode('['.$embedded_shortcode.']');\n }\n }\n return $logged_in_content; \n }\n\nadd_shortcode('logged-in-content','content_for_logged_in');\n</code></pre>\n\n<p>and then this:</p>\n\n<pre><code>[logged-in-content embedded_shortcode=\"wpforms id=752\"]\n &lt;p&gt;Use the form below to upload photos for the Photo Galleries page.&lt;/p&gt;\n[/logged-in-content]\n</code></pre>\n\n<p>I’d still be interested if there’s a way to do it so that the actual shortcode can be within the $content area of the enclosing shortcode in case sometime I want to do it so that I can place the embedded shortcode somewhere else within the content, or can do multiple shortcodes within the $content area.</p>\n\n<p>For my immediate needs, the above solution does the trick.</p>\n" }, { "answer_id": 359667, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 2, "selected": true, "text": "<p>The function you are looking for is named <code>do_shortcode</code> (there will also be a function <code>apply_shortcode</code> in Wordpress 5.4 that does the same). <a href=\"https://developer.wordpress.org/reference/functions/do_shortcode/\" rel=\"nofollow noreferrer\">Codex Page</a></p>\n\n<p>For your example, this will work:</p>\n\n<pre><code>function content_for_logged_in($atts,$content){\n $logged_in_content = \"\";\n if(is_user_logged_in()){\n $logged_in_content = do_shortcode($content);\n }\n return $logged_in_content; \n}\nadd_shortcode('logged-in-content','content_for_logged_in');\n</code></pre>\n\n<p>Happy Coding!</p>\n" } ]
2020/02/28
[ "https://wordpress.stackexchange.com/questions/359660", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57399/" ]
I've created a quick function and shortcode to allow me to include logged-in user only content: ``` function content_for_logged_in($atts,$content){ $logged_in_content = ""; if(is_user_logged_in()){ $logged_in_content = $content; } return $logged_in_content; } add_shortcode('logged-in-content','content_for_logged_in'); ``` But it doesn't parse shortcodes that are within the content, e.g.: ``` [logged-in-content] <p>Some test content...</p> [wpforms id="752"] [/logged-in-content] ``` ...in this case, the wpforms shortcode is displayed rather than the form. Is there a way to alter my function so that shortcodes within the content will be parsed? Thanks, Scott
The function you are looking for is named `do_shortcode` (there will also be a function `apply_shortcode` in Wordpress 5.4 that does the same). [Codex Page](https://developer.wordpress.org/reference/functions/do_shortcode/) For your example, this will work: ``` function content_for_logged_in($atts,$content){ $logged_in_content = ""; if(is_user_logged_in()){ $logged_in_content = do_shortcode($content); } return $logged_in_content; } add_shortcode('logged-in-content','content_for_logged_in'); ``` Happy Coding!
359,665
<p>I have used custom php form for uploading image via ajax. And has successfully uploaded the image and getting the attachment id &amp; the image url also,</p> <p>Is there any way to attach the attachment id or the image url to the user profile image, so the admin can also view the user profile image in user list. </p> <p>Thanks. </p>
[ { "answer_id": 359661, "author": "ScottM", "author_id": 57399, "author_profile": "https://wordpress.stackexchange.com/users/57399", "pm_score": 0, "selected": false, "text": "<p>I found a way to achieve what I need right now...</p>\n\n<pre><code> function content_for_logged_in($atts,$content){\n $logged_in_content = \"\";\n $embedded_shortcode = $atts['embedded_shortcode'];\n if(is_user_logged_in()){\n $logged_in_content = $content;\n if(!empty($embedded_shortcode)) {\n $logged_in_content .= do_shortcode('['.$embedded_shortcode.']');\n }\n }\n return $logged_in_content; \n }\n\nadd_shortcode('logged-in-content','content_for_logged_in');\n</code></pre>\n\n<p>and then this:</p>\n\n<pre><code>[logged-in-content embedded_shortcode=\"wpforms id=752\"]\n &lt;p&gt;Use the form below to upload photos for the Photo Galleries page.&lt;/p&gt;\n[/logged-in-content]\n</code></pre>\n\n<p>I’d still be interested if there’s a way to do it so that the actual shortcode can be within the $content area of the enclosing shortcode in case sometime I want to do it so that I can place the embedded shortcode somewhere else within the content, or can do multiple shortcodes within the $content area.</p>\n\n<p>For my immediate needs, the above solution does the trick.</p>\n" }, { "answer_id": 359667, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 2, "selected": true, "text": "<p>The function you are looking for is named <code>do_shortcode</code> (there will also be a function <code>apply_shortcode</code> in Wordpress 5.4 that does the same). <a href=\"https://developer.wordpress.org/reference/functions/do_shortcode/\" rel=\"nofollow noreferrer\">Codex Page</a></p>\n\n<p>For your example, this will work:</p>\n\n<pre><code>function content_for_logged_in($atts,$content){\n $logged_in_content = \"\";\n if(is_user_logged_in()){\n $logged_in_content = do_shortcode($content);\n }\n return $logged_in_content; \n}\nadd_shortcode('logged-in-content','content_for_logged_in');\n</code></pre>\n\n<p>Happy Coding!</p>\n" } ]
2020/02/28
[ "https://wordpress.stackexchange.com/questions/359665", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/170387/" ]
I have used custom php form for uploading image via ajax. And has successfully uploaded the image and getting the attachment id & the image url also, Is there any way to attach the attachment id or the image url to the user profile image, so the admin can also view the user profile image in user list. Thanks.
The function you are looking for is named `do_shortcode` (there will also be a function `apply_shortcode` in Wordpress 5.4 that does the same). [Codex Page](https://developer.wordpress.org/reference/functions/do_shortcode/) For your example, this will work: ``` function content_for_logged_in($atts,$content){ $logged_in_content = ""; if(is_user_logged_in()){ $logged_in_content = do_shortcode($content); } return $logged_in_content; } add_shortcode('logged-in-content','content_for_logged_in'); ``` Happy Coding!
359,695
<p>I'm trying and failing to register an embed code for content from padlet.com (strangely it's supported in WP.com but not WP.org). A URL like</p> <pre><code> https://padlet.com/cogdogblog/aos9fosbbwk4 </code></pre> <p>should embed like</p> <pre class="lang-html prettyprint-override"><code>&lt;div class="padlet-embed" style="border:1px solid rgba(0,0,0,0.1);border-radius:2px;box-sizing:border-box;overflow:hidden;position:relative;width:100%;background:#F4F4F4"&gt;&lt;p style="padding:0;margin:0"&gt;&lt;iframe src="https://padlet.com/embed/aos9fosbbwk4" frameborder="0" allow="camera;microphone;geolocation" style="width:100%;height:608px;display:block;padding:0;margin:0"&gt;&lt;/iframe&gt;&lt;/p&gt; </code></pre> <p>My attempt that fails so far</p> <pre class="lang-php prettyprint-override"><code>add_action( 'init', function(){ $regex_url = '#https?://padlet\.com/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$#i'; wp_embed_register_handler( 'padlet', $regex_url, 'wp_embed_handler_padlet', true ); }); function wp_embed_handler_padlet( $matches, $attr, $url, $rawattr ) { $embed = sprintf( '&lt;div class="padlet-embed" style="border:1px solid rgba(0,0,0,0.1);border-radius:2px;box-sizing:border-box;overflow:hidden;position:relative;width:100%;background:#F4F4F4"&gt;&lt;p style="padding:0;margin:0"&gt;&lt;iframe src="https://padlet.com/embed/%1$s" frameborder="0" allow="camera;microphone;geolocation" style="width:100%;height:608px;display:block;padding:0;margin:0"&gt;&lt;/iframe&gt;&lt;/p&gt;', esc_attr($matches[2]) ); return apply_filters( 'embed_padlet', $embed, $matches, $attr, $url, $rawattr ); } </code></pre> <p>I am sure it is my regex clumsiness. It would sure help newbies like me if the <a href="https://codex.wordpress.org/Function_Reference/wp_embed_register_handler" rel="nofollow noreferrer">Codex docs for this function</a> had a better explained (and actually working) example.</p> <p>And what form of regex is used in <code>wp_embed_register_handler</code>? None of the online testers I use have this format and requires escaping of <code>/</code> - looking for a place to test patterns that WordPress uses.</p> <p><strong>UPDATE</strong> After failing to find Padlet listed as an oembed provider <a href="https://oembed.com/" rel="nofollow noreferrer">https://oembed.com/</a> and not finding any documentation on their developer site <a href="https://padlet.readme.io/" rel="nofollow noreferrer">https://padlet.readme.io/</a> I decided to wild guess at the URL for an oembed request from the format</p> <pre><code> https://padlet.com/oembed?url=https%3A//padlet.com/XXXXXX/yyyyyyyyyy&amp;format=json </code></pre> <p>or a real example </p> <p><a href="https://padlet.com/oembed?url=https%3A//padlet.com/cogdogblog/aos9fosbbwk4&amp;format=json" rel="nofollow noreferrer">https://padlet.com/oembed?url=https%3A//padlet.com/cogdogblog/aos9fosbbwk4&amp;format=json</a></p> <p>And I get a response (this makes sense as this is how WordPress.com is likely supporting it). So now I get full support via the much simpler:</p> <pre class="lang-php prettyprint-override"><code>wp_oembed_add_provider( "https://padlet.com/*", "https://padlet.com/oembed/", false ); </code></pre>
[ { "answer_id": 359696, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Have you considered using a simpler regex such as:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>'#^https?://padlet\\.com/(\\?.+)?$#'\n</code></pre>\n\n<p>Then breaking apart the latter section with <code>explode</code> to get the video ID?</p>\n" }, { "answer_id": 359699, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 0, "selected": false, "text": "<p>I think the issue is that the inline styles on the <code>&lt;iframe&gt;</code> are causing the embed to choke due to WP's sanitizing of the HTML. I was able to get the embed to work once I removed the inline styles and balanced the HTML tags:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code> add_action( 'init', function(){\n $regex_url = '#https?://padlet\\.com/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$#i';\n\n wp_embed_register_handler(\n 'padlet',\n $regex_url,\n 'wp_embed_handler_padlet',\n true\n );\n });\n\n\n function wp_embed_handler_padlet( $matches, $attr, $url, $rawattr ) {\n $embed = sprintf(\n '&lt;div class=\"padlet-embed\"&gt;\n &lt;iframe src=\"//padlet.com/embed/%1$s\" frameborder=\"0\" allow=\"camera;microphone;geolocation\"&gt;&lt;/iframe&gt;\n &lt;/div&gt;',\n esc_attr($matches[2])\n );\n\n return apply_filters( 'embed_padlet', $embed, $matches, $attr, $url, $rawattr );\n }\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/tHCo7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tHCo7.png\" alt=\"padlet embed example\"></a></p>\n\n<p>You can style the embed by targeting <code>.padlet-embed</code> in your CSS rather than adding the styles inline.</p>\n\n<p>Edit: Tested in the block editor and it works on both the backend and frontend without any changes but you need to use the embed block.\n<a href=\"https://i.stack.imgur.com/DSCHH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DSCHH.png\" alt=\"enter image description here\"></a>\n<a href=\"https://i.stack.imgur.com/HbHDD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HbHDD.png\" alt=\"enter image description here\"></a></p>\n" } ]
2020/02/28
[ "https://wordpress.stackexchange.com/questions/359695", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14945/" ]
I'm trying and failing to register an embed code for content from padlet.com (strangely it's supported in WP.com but not WP.org). A URL like ``` https://padlet.com/cogdogblog/aos9fosbbwk4 ``` should embed like ```html <div class="padlet-embed" style="border:1px solid rgba(0,0,0,0.1);border-radius:2px;box-sizing:border-box;overflow:hidden;position:relative;width:100%;background:#F4F4F4"><p style="padding:0;margin:0"><iframe src="https://padlet.com/embed/aos9fosbbwk4" frameborder="0" allow="camera;microphone;geolocation" style="width:100%;height:608px;display:block;padding:0;margin:0"></iframe></p> ``` My attempt that fails so far ```php add_action( 'init', function(){ $regex_url = '#https?://padlet\.com/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$#i'; wp_embed_register_handler( 'padlet', $regex_url, 'wp_embed_handler_padlet', true ); }); function wp_embed_handler_padlet( $matches, $attr, $url, $rawattr ) { $embed = sprintf( '<div class="padlet-embed" style="border:1px solid rgba(0,0,0,0.1);border-radius:2px;box-sizing:border-box;overflow:hidden;position:relative;width:100%;background:#F4F4F4"><p style="padding:0;margin:0"><iframe src="https://padlet.com/embed/%1$s" frameborder="0" allow="camera;microphone;geolocation" style="width:100%;height:608px;display:block;padding:0;margin:0"></iframe></p>', esc_attr($matches[2]) ); return apply_filters( 'embed_padlet', $embed, $matches, $attr, $url, $rawattr ); } ``` I am sure it is my regex clumsiness. It would sure help newbies like me if the [Codex docs for this function](https://codex.wordpress.org/Function_Reference/wp_embed_register_handler) had a better explained (and actually working) example. And what form of regex is used in `wp_embed_register_handler`? None of the online testers I use have this format and requires escaping of `/` - looking for a place to test patterns that WordPress uses. **UPDATE** After failing to find Padlet listed as an oembed provider <https://oembed.com/> and not finding any documentation on their developer site <https://padlet.readme.io/> I decided to wild guess at the URL for an oembed request from the format ``` https://padlet.com/oembed?url=https%3A//padlet.com/XXXXXX/yyyyyyyyyy&format=json ``` or a real example <https://padlet.com/oembed?url=https%3A//padlet.com/cogdogblog/aos9fosbbwk4&format=json> And I get a response (this makes sense as this is how WordPress.com is likely supporting it). So now I get full support via the much simpler: ```php wp_oembed_add_provider( "https://padlet.com/*", "https://padlet.com/oembed/", false ); ```
Have you considered using a simpler regex such as: ```php '#^https?://padlet\.com/(\?.+)?$#' ``` Then breaking apart the latter section with `explode` to get the video ID?
359,737
<p>I want to be able to change the WordPress default logo url (not the logo image) based on the user role. The image/logo will remain the same, only the url will change. Any assistance or ideas will be greatly appreciated.</p>
[ { "answer_id": 359696, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Have you considered using a simpler regex such as:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>'#^https?://padlet\\.com/(\\?.+)?$#'\n</code></pre>\n\n<p>Then breaking apart the latter section with <code>explode</code> to get the video ID?</p>\n" }, { "answer_id": 359699, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 0, "selected": false, "text": "<p>I think the issue is that the inline styles on the <code>&lt;iframe&gt;</code> are causing the embed to choke due to WP's sanitizing of the HTML. I was able to get the embed to work once I removed the inline styles and balanced the HTML tags:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code> add_action( 'init', function(){\n $regex_url = '#https?://padlet\\.com/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$#i';\n\n wp_embed_register_handler(\n 'padlet',\n $regex_url,\n 'wp_embed_handler_padlet',\n true\n );\n });\n\n\n function wp_embed_handler_padlet( $matches, $attr, $url, $rawattr ) {\n $embed = sprintf(\n '&lt;div class=\"padlet-embed\"&gt;\n &lt;iframe src=\"//padlet.com/embed/%1$s\" frameborder=\"0\" allow=\"camera;microphone;geolocation\"&gt;&lt;/iframe&gt;\n &lt;/div&gt;',\n esc_attr($matches[2])\n );\n\n return apply_filters( 'embed_padlet', $embed, $matches, $attr, $url, $rawattr );\n }\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/tHCo7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tHCo7.png\" alt=\"padlet embed example\"></a></p>\n\n<p>You can style the embed by targeting <code>.padlet-embed</code> in your CSS rather than adding the styles inline.</p>\n\n<p>Edit: Tested in the block editor and it works on both the backend and frontend without any changes but you need to use the embed block.\n<a href=\"https://i.stack.imgur.com/DSCHH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DSCHH.png\" alt=\"enter image description here\"></a>\n<a href=\"https://i.stack.imgur.com/HbHDD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HbHDD.png\" alt=\"enter image description here\"></a></p>\n" } ]
2020/02/29
[ "https://wordpress.stackexchange.com/questions/359737", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183556/" ]
I want to be able to change the WordPress default logo url (not the logo image) based on the user role. The image/logo will remain the same, only the url will change. Any assistance or ideas will be greatly appreciated.
Have you considered using a simpler regex such as: ```php '#^https?://padlet\.com/(\?.+)?$#' ``` Then breaking apart the latter section with `explode` to get the video ID?
359,744
<p>I have installed wordpress on google compute engine..</p> <p>Running nginx, wordpress and https.. The site doesn't load the admin panel or the images..</p> <p>throws up 404 error on chrome inspection </p> <blockquote> <p>HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier). GET - <a href="https://fadingfernphotography.ca/api/wordpress/wp-content/uploads/2020/01/blog-1-1568x1046.png" rel="nofollow noreferrer">https://fadingfernphotography.ca/api/wordpress/wp-content/uploads/2020/01/blog-1-1568x1046.png</a></p> <p>HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier). GET - <a href="https://fadingfernphotography.ca/api/wordpress/wp-content/uploads/2020/01/Blog-1-1568x1263.png" rel="nofollow noreferrer">https://fadingfernphotography.ca/api/wordpress/wp-content/uploads/2020/01/Blog-1-1568x1263.png</a></p> </blockquote>
[ { "answer_id": 359696, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Have you considered using a simpler regex such as:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>'#^https?://padlet\\.com/(\\?.+)?$#'\n</code></pre>\n\n<p>Then breaking apart the latter section with <code>explode</code> to get the video ID?</p>\n" }, { "answer_id": 359699, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 0, "selected": false, "text": "<p>I think the issue is that the inline styles on the <code>&lt;iframe&gt;</code> are causing the embed to choke due to WP's sanitizing of the HTML. I was able to get the embed to work once I removed the inline styles and balanced the HTML tags:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code> add_action( 'init', function(){\n $regex_url = '#https?://padlet\\.com/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$#i';\n\n wp_embed_register_handler(\n 'padlet',\n $regex_url,\n 'wp_embed_handler_padlet',\n true\n );\n });\n\n\n function wp_embed_handler_padlet( $matches, $attr, $url, $rawattr ) {\n $embed = sprintf(\n '&lt;div class=\"padlet-embed\"&gt;\n &lt;iframe src=\"//padlet.com/embed/%1$s\" frameborder=\"0\" allow=\"camera;microphone;geolocation\"&gt;&lt;/iframe&gt;\n &lt;/div&gt;',\n esc_attr($matches[2])\n );\n\n return apply_filters( 'embed_padlet', $embed, $matches, $attr, $url, $rawattr );\n }\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/tHCo7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tHCo7.png\" alt=\"padlet embed example\"></a></p>\n\n<p>You can style the embed by targeting <code>.padlet-embed</code> in your CSS rather than adding the styles inline.</p>\n\n<p>Edit: Tested in the block editor and it works on both the backend and frontend without any changes but you need to use the embed block.\n<a href=\"https://i.stack.imgur.com/DSCHH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DSCHH.png\" alt=\"enter image description here\"></a>\n<a href=\"https://i.stack.imgur.com/HbHDD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HbHDD.png\" alt=\"enter image description here\"></a></p>\n" } ]
2020/02/29
[ "https://wordpress.stackexchange.com/questions/359744", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183558/" ]
I have installed wordpress on google compute engine.. Running nginx, wordpress and https.. The site doesn't load the admin panel or the images.. throws up 404 error on chrome inspection > > HTTP404: NOT FOUND - The server has not found anything matching the > requested URI (Uniform Resource Identifier). GET - > <https://fadingfernphotography.ca/api/wordpress/wp-content/uploads/2020/01/blog-1-1568x1046.png> > > > HTTP404: NOT FOUND - The server has not found anything matching the > requested URI (Uniform Resource Identifier). GET - > <https://fadingfernphotography.ca/api/wordpress/wp-content/uploads/2020/01/Blog-1-1568x1263.png> > > >
Have you considered using a simpler regex such as: ```php '#^https?://padlet\.com/(\?.+)?$#' ``` Then breaking apart the latter section with `explode` to get the video ID?
359,762
<p>I ama newbie in WordPress Plugin development in which I have some HTML form on the main plugin page that will get the data from the admin who is logged in and a back page where I have some different functions in PHP like to get information from the database etc. To explain in detail, here is the code...</p> <p><strong>Main Plugin File:</strong></p> <pre><code>&lt;?php /* Plugin Name: WP Testing Plugin Plugin URI: http://www.wordpress.org/WP-Testing-Plugin Description: A Detailed Description About This Plugin. Author: Muhammad Hassan Version: 0.1 Author URI: http://www.wordpress.org */ /*____________WP Testing Plugin Admin/Script_____________*/ function wp_testingPlugin_admin() { echo ' &lt;form id="searchForm" onsubmit="return searchData(this)"&gt; &lt;input name="WhatToSearch" type="text" /&gt; &lt;input type="submit" value="Search"/&gt; &lt;input type="reset" value="Reset"/&gt; &lt;div id="showReturnData"&gt;&lt;/div&gt; &lt;/form&gt; '; echo ' &lt;form id="infoForm" onsubmit="return searchInfo(this)"&gt; &lt;input name="WhatToKnow" type="text" /&gt; &lt;input type="submit" value="Search"/&gt; &lt;input type="reset" value="Reset"/&gt; &lt;div id="showReturnInfo"&gt;&lt;/div&gt; &lt;/form&gt; '; echo ' &lt;script type="text/javascript"&gt; function searchData(incomingForm) { // Confirmation To Add A Data var answer = confirm("Are You Sure Want To Search?"); if (answer){ // If User Click Ok Then Execute The Below Code var FD = new FormData(incomingForm); // Get FORM Element Object FD.append("Function", "DataFunction"); // Adding Extra Data In FORM Element Object To Hit Only This Function In Ajax Call File var ajx = new XMLHttpRequest(); ajx.onreadystatechange = function () { if (ajx.readyState == 4 &amp;&amp; ajx.status == 200) { document.getElementById("showReturnData").innerHTML = ajx.responseText; } }; ajx.open("POST", "'.plugin_dir_url( __FILE__ ).'my_functions.php", true); ajx.send(FD); document.getElementById("showReturnData").innerHTML = "&lt;div class="error"&gt;ERROR: AJAX Did Not Respond.&lt;/div&gt;"; } return false; // For Not To Reload Page } function searchInfo(incomingForm) { // Confirmation To Add A Data var answer = confirm("Are You Sure Want To Search?"); if (answer){ // If User Click Ok Then Execute The Below Code var FD = new FormData(incomingForm); // Get FORM Element Object FD.append("Function", "InfoFunction"); // Adding Extra Data In FORM Element Object To Hit Only This Function In Ajax Call File var ajx = new XMLHttpRequest(); ajx.onreadystatechange = function () { if (ajx.readyState == 4 &amp;&amp; ajx.status == 200) { document.getElementById("showReturnData").innerHTML = ajx.responseText; } }; ajx.open("POST", "'.plugin_dir_url( __FILE__ ).'my_functions.php", true); ajx.send(FD); document.getElementById("showReturnInfo").innerHTML = "&lt;div class="error"&gt;ERROR: AJAX Did Not Respond.&lt;/div&gt;"; } return false; // For Not To Reload Page } &lt;/script&gt; '; //if you want only logged in users to access this function use this hook add_action('wp_ajax_searchData', 'searchData'); add_action('wp_ajax_searchInfo', 'searchInfo'); //if you want none logged in users to access this function use this hook add_action('wp_ajax_nopriv_searchData', 'searchData'); add_action('wp_ajax_nopriv_searchInfo', 'searchInfo'); } /*__________________________________________________________________*/ /*____________WP Testing Plugin Option_____________*/ //Adding "WP Testing Plugin" Menu To WordPress -&gt; Tools function wp_testingPlugin() { // add_management_page( $page_title, $menu_title, $capability, $menu_slug, $function); Menu Under Tools add_management_page("WP Testing Plugin By Hassan", "WP Testing Plugin", 'activate_plugins', "WP-Testing-Plugin", "wp_testingPlugin_admin"); } add_action('admin_menu', 'wp_testingPlugin'); /*__________________________________________________________________*/ ?&gt; </code></pre> <p>And this is <strong>my_functions.php</strong> file.</p> <pre><code>&lt;?php /****************************************************************************/ //Garb The Function Parameter /****************************************************************************/ $Function = $_POST['Function']; /****************************************************************************/ // Run Search Function /****************************************************************************/ if ($Function == "DataFunction"){ if(!isset($_POST['WhatToSearch'])){ $WhatToSearch = "Nothing"; } else { $WhatToSearch = $_POST['WhatToSearch']; } echo "&lt;div class='success'&gt;SUCCESS: Function Is Working Perfectly And Getting Data ".$WhatToSearch.".&lt;/div&gt;"; } /****************************************************************************/ // Run Another Function /****************************************************************************/ if ($Function == "InfoFunction"){ if(!isset($_POST['WhatToKnow'])){ $WhatToKnow = "Nothing"; } else { $WhatToKnow = $_POST['WhatToKnow']; } echo "&lt;div class='success'&gt;SUCCESS: Function Is Working Perfectly And Getting Data ".$WhatToKnow.".&lt;/div&gt;"; } ?&gt; </code></pre> <p>But my code is not working and not hitting <code>my_functions.php</code> file even. Whats the problem here? Need basic step only to work in this patteren. Currently, I am not sure I am even implementing this correctly as I never used WP AJAX before. So right now, my objective is just to get a basic example working. I appreciate any suggestions on how to accomplish this.</p> <p>Thank you!</p>
[ { "answer_id": 360242, "author": "Muhammad Hassan", "author_id": 52859, "author_profile": "https://wordpress.stackexchange.com/users/52859", "pm_score": 1, "selected": true, "text": "<p>Finally after trying my best, here I am sharing the working complete basic example of my question in easy steps. This answer is also considered as a full Ajax Plugin Example in a professional way. I now recommend keeping every file separate for better, clean and comfortable coding...</p>\n\n<p><strong>Main Plugin File:</strong></p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: WP Testing Plugin\nPlugin URI: http://www.wordpress.org/WP-Testing-Plugin\nDescription: A Detailed Description About This Plugin.\nAuthor: Muhammad Hassan\nVersion: 0.1\nAuthor URI: http://www.wordpress.org\n*/\n\n// Calling All PHP File To Load\ninclude('my_functions.php');\n\n/*____________WP Testing Plugin Admin/Script_____________*/\nfunction wp_testingPlugin_admin() {\n echo '\n &lt;form id=\"searchForm\"&gt;\n &lt;input name=\"WhatToSearch\" type=\"text\" /&gt;\n &lt;input type=\"submit\" value=\"Search\"/&gt;\n &lt;input type=\"reset\" value=\"Reset\"/&gt;\n &lt;div id=\"showReturnData\"&gt;&lt;/div&gt;\n &lt;/form&gt;\n ';\n}\n/*__________________________________________________________________*/\n\n/*____________WP Testing Plugin Option_____________*/\n//Adding \"WP Testing Plugin\" Menu To WordPress -&gt; Tools\nfunction wp_testingPlugin() {\n // add_management_page( $page_title, $menu_title, $capability, $menu_slug, $function); Menu Under Tools\n add_management_page(\"WP Testing Plugin By Hassan\", \"WP Testing Plugin\", 'activate_plugins', \"WP-Testing-Plugin\", \"wp_testingPlugin_admin\");\n}\nadd_action('admin_menu', 'wp_testingPlugin');\n/*__________________________________________________________________*/\n?&gt;\n</code></pre>\n\n<p><strong>my_functions.php</strong></p>\n\n<pre><code>&lt;?php\nadd_action( 'admin_enqueue_scripts', 'my_enqueue' );\nfunction my_enqueue() {\n wp_enqueue_script( 'ajax-script', plugin_dir_url( __FILE__ ).'my_javascript.js', array('jquery') );\n wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' =&gt; admin_url( 'admin-ajax.php' ) ) );\n}\n/****************************************************************************/\n// Run Search Function\n/****************************************************************************/\n/* Register This Function When This File Is Loaded To Call By WordPress AJAX */\nadd_action('wp_ajax_nopriv_SearchFunction', 'ajaxSearchFunction'); // For Web Visitors\nadd_action('wp_ajax_SearchFunction', 'ajaxSearchFunction'); // For Admin User\nfunction ajaxSearchFunction(){\n if($_POST['WhatToSearch'] == \"\"){\n $WhatToSearch = \"Nothing\";\n } else {\n $WhatToSearch = $_POST['WhatToSearch'];\n }\n echo \"&lt;div class='success'&gt;SUCCESS: Function Is Working Perfectly And Getting Data \".$WhatToSearch.\".&lt;/div&gt;\";\n}\n?&gt;\n</code></pre>\n\n<p><strong>my_javascript.js</strong></p>\n\n<pre><code>jQuery(document).ready(function() {\njQuery('#searchForm').on(\"submit\",function(e) {\nvar incomingData = jQuery('#searchForm').serializeArray();\nincomingData.push({name: 'action', value: 'SearchFunction'});\nalert(JSON.stringify(incomingData));\njQuery.ajax({\ntype: 'post',\nurl: my_ajax_object.ajax_url,\ndata: incomingData,\nsuccess: function(response) {\njQuery('#showReturnData').html(response);\n},\nerror: function(response) {\njQuery('#showReturnData').html('&lt;div\"&gt;Error&lt;/div&gt;');\n},\n});\nreturn false; // For Not To Reload Page\n});\n});\n</code></pre>\n\n<p>Thanks for reading this.</p>\n" }, { "answer_id": 361499, "author": "Dennis Bowtell", "author_id": 184862, "author_profile": "https://wordpress.stackexchange.com/users/184862", "pm_score": 1, "selected": false, "text": "<p>Thanks Muhammad,\nYour solution is a fantastic working framework on which to base real world AJAX calls.\nI just added this code to the plugin main php file for a shortcode so I could use it in the Front End too.</p>\n\n<pre><code>//For front end use in production\nadd_shortcode('wp_testingPlugin_shortcode', 'wp_testingPlugin_shortcode');\nfunction wp_testingPlugin_shortcode() {\n wp_enqueue_script( 'ajax-script', plugin_dir_url( __FILE__ ).'my_javascript.js', array('jquery') );\n wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' =&gt; admin_url( 'admin-ajax.php' ) ) );\n return '&lt;form id=\"searchForm\"&gt;\n &lt;input name=\"WhatToSearch\" type=\"text\" /&gt;\n &lt;input type=\"submit\" value=\"Search\"/&gt;\n &lt;input type=\"reset\" value=\"Reset\"/&gt;\n &lt;div id=\"showReturnData\"&gt;&lt;/div&gt;\n &lt;/form&gt;';\n}\n</code></pre>\n" } ]
2020/02/29
[ "https://wordpress.stackexchange.com/questions/359762", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52859/" ]
I ama newbie in WordPress Plugin development in which I have some HTML form on the main plugin page that will get the data from the admin who is logged in and a back page where I have some different functions in PHP like to get information from the database etc. To explain in detail, here is the code... **Main Plugin File:** ``` <?php /* Plugin Name: WP Testing Plugin Plugin URI: http://www.wordpress.org/WP-Testing-Plugin Description: A Detailed Description About This Plugin. Author: Muhammad Hassan Version: 0.1 Author URI: http://www.wordpress.org */ /*____________WP Testing Plugin Admin/Script_____________*/ function wp_testingPlugin_admin() { echo ' <form id="searchForm" onsubmit="return searchData(this)"> <input name="WhatToSearch" type="text" /> <input type="submit" value="Search"/> <input type="reset" value="Reset"/> <div id="showReturnData"></div> </form> '; echo ' <form id="infoForm" onsubmit="return searchInfo(this)"> <input name="WhatToKnow" type="text" /> <input type="submit" value="Search"/> <input type="reset" value="Reset"/> <div id="showReturnInfo"></div> </form> '; echo ' <script type="text/javascript"> function searchData(incomingForm) { // Confirmation To Add A Data var answer = confirm("Are You Sure Want To Search?"); if (answer){ // If User Click Ok Then Execute The Below Code var FD = new FormData(incomingForm); // Get FORM Element Object FD.append("Function", "DataFunction"); // Adding Extra Data In FORM Element Object To Hit Only This Function In Ajax Call File var ajx = new XMLHttpRequest(); ajx.onreadystatechange = function () { if (ajx.readyState == 4 && ajx.status == 200) { document.getElementById("showReturnData").innerHTML = ajx.responseText; } }; ajx.open("POST", "'.plugin_dir_url( __FILE__ ).'my_functions.php", true); ajx.send(FD); document.getElementById("showReturnData").innerHTML = "<div class="error">ERROR: AJAX Did Not Respond.</div>"; } return false; // For Not To Reload Page } function searchInfo(incomingForm) { // Confirmation To Add A Data var answer = confirm("Are You Sure Want To Search?"); if (answer){ // If User Click Ok Then Execute The Below Code var FD = new FormData(incomingForm); // Get FORM Element Object FD.append("Function", "InfoFunction"); // Adding Extra Data In FORM Element Object To Hit Only This Function In Ajax Call File var ajx = new XMLHttpRequest(); ajx.onreadystatechange = function () { if (ajx.readyState == 4 && ajx.status == 200) { document.getElementById("showReturnData").innerHTML = ajx.responseText; } }; ajx.open("POST", "'.plugin_dir_url( __FILE__ ).'my_functions.php", true); ajx.send(FD); document.getElementById("showReturnInfo").innerHTML = "<div class="error">ERROR: AJAX Did Not Respond.</div>"; } return false; // For Not To Reload Page } </script> '; //if you want only logged in users to access this function use this hook add_action('wp_ajax_searchData', 'searchData'); add_action('wp_ajax_searchInfo', 'searchInfo'); //if you want none logged in users to access this function use this hook add_action('wp_ajax_nopriv_searchData', 'searchData'); add_action('wp_ajax_nopriv_searchInfo', 'searchInfo'); } /*__________________________________________________________________*/ /*____________WP Testing Plugin Option_____________*/ //Adding "WP Testing Plugin" Menu To WordPress -> Tools function wp_testingPlugin() { // add_management_page( $page_title, $menu_title, $capability, $menu_slug, $function); Menu Under Tools add_management_page("WP Testing Plugin By Hassan", "WP Testing Plugin", 'activate_plugins', "WP-Testing-Plugin", "wp_testingPlugin_admin"); } add_action('admin_menu', 'wp_testingPlugin'); /*__________________________________________________________________*/ ?> ``` And this is **my\_functions.php** file. ``` <?php /****************************************************************************/ //Garb The Function Parameter /****************************************************************************/ $Function = $_POST['Function']; /****************************************************************************/ // Run Search Function /****************************************************************************/ if ($Function == "DataFunction"){ if(!isset($_POST['WhatToSearch'])){ $WhatToSearch = "Nothing"; } else { $WhatToSearch = $_POST['WhatToSearch']; } echo "<div class='success'>SUCCESS: Function Is Working Perfectly And Getting Data ".$WhatToSearch.".</div>"; } /****************************************************************************/ // Run Another Function /****************************************************************************/ if ($Function == "InfoFunction"){ if(!isset($_POST['WhatToKnow'])){ $WhatToKnow = "Nothing"; } else { $WhatToKnow = $_POST['WhatToKnow']; } echo "<div class='success'>SUCCESS: Function Is Working Perfectly And Getting Data ".$WhatToKnow.".</div>"; } ?> ``` But my code is not working and not hitting `my_functions.php` file even. Whats the problem here? Need basic step only to work in this patteren. Currently, I am not sure I am even implementing this correctly as I never used WP AJAX before. So right now, my objective is just to get a basic example working. I appreciate any suggestions on how to accomplish this. Thank you!
Finally after trying my best, here I am sharing the working complete basic example of my question in easy steps. This answer is also considered as a full Ajax Plugin Example in a professional way. I now recommend keeping every file separate for better, clean and comfortable coding... **Main Plugin File:** ``` <?php /* Plugin Name: WP Testing Plugin Plugin URI: http://www.wordpress.org/WP-Testing-Plugin Description: A Detailed Description About This Plugin. Author: Muhammad Hassan Version: 0.1 Author URI: http://www.wordpress.org */ // Calling All PHP File To Load include('my_functions.php'); /*____________WP Testing Plugin Admin/Script_____________*/ function wp_testingPlugin_admin() { echo ' <form id="searchForm"> <input name="WhatToSearch" type="text" /> <input type="submit" value="Search"/> <input type="reset" value="Reset"/> <div id="showReturnData"></div> </form> '; } /*__________________________________________________________________*/ /*____________WP Testing Plugin Option_____________*/ //Adding "WP Testing Plugin" Menu To WordPress -> Tools function wp_testingPlugin() { // add_management_page( $page_title, $menu_title, $capability, $menu_slug, $function); Menu Under Tools add_management_page("WP Testing Plugin By Hassan", "WP Testing Plugin", 'activate_plugins', "WP-Testing-Plugin", "wp_testingPlugin_admin"); } add_action('admin_menu', 'wp_testingPlugin'); /*__________________________________________________________________*/ ?> ``` **my\_functions.php** ``` <?php add_action( 'admin_enqueue_scripts', 'my_enqueue' ); function my_enqueue() { wp_enqueue_script( 'ajax-script', plugin_dir_url( __FILE__ ).'my_javascript.js', array('jquery') ); wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); } /****************************************************************************/ // Run Search Function /****************************************************************************/ /* Register This Function When This File Is Loaded To Call By WordPress AJAX */ add_action('wp_ajax_nopriv_SearchFunction', 'ajaxSearchFunction'); // For Web Visitors add_action('wp_ajax_SearchFunction', 'ajaxSearchFunction'); // For Admin User function ajaxSearchFunction(){ if($_POST['WhatToSearch'] == ""){ $WhatToSearch = "Nothing"; } else { $WhatToSearch = $_POST['WhatToSearch']; } echo "<div class='success'>SUCCESS: Function Is Working Perfectly And Getting Data ".$WhatToSearch.".</div>"; } ?> ``` **my\_javascript.js** ``` jQuery(document).ready(function() { jQuery('#searchForm').on("submit",function(e) { var incomingData = jQuery('#searchForm').serializeArray(); incomingData.push({name: 'action', value: 'SearchFunction'}); alert(JSON.stringify(incomingData)); jQuery.ajax({ type: 'post', url: my_ajax_object.ajax_url, data: incomingData, success: function(response) { jQuery('#showReturnData').html(response); }, error: function(response) { jQuery('#showReturnData').html('<div">Error</div>'); }, }); return false; // For Not To Reload Page }); }); ``` Thanks for reading this.
359,766
<p>I’ve got a simple php script which is connecting to my wordpress to create a product. Using the woocommerce rest api library.</p> <pre><code>$woocommerce = new Client( 'https://dev.example.co.uk', '123456789', '123456789', [ 'wp_api' =&gt; true, 'version' =&gt; 'wc/v3', 'sslverify' =&gt; false, ] ); // foreach item $woocommerce-&gt;post( 'products', $data ); </code></pre> <blockquote> <p>Fatal error: Uncaught Automattic\WooCommerce\HttpClient\HttpClientException: cURL Error: SSL certificate problem: self signed certificate in /srv/www/example.co.uk/current/web/app/themes/exampletheme/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php on line 417</p> </blockquote> <p>I’ve attempted the following: Get the certificate from the dev site:</p> <pre><code>openssl s_client -connect example.co.uk:443 | tee logfile </code></pre> <p>Copied the certificate and made a file from it called <strong>certificate.crt</strong></p> <pre><code>MIICyTCCAbGgAwIBAgIJANB2.... </code></pre> <p>Uploaded to: </p> <pre><code>/srv/www/example.co.uk/current/web/wp/certificate.crt </code></pre> <p>And now trying to use it to prevent this error. <strong>functions.php</strong></p> <pre><code>add_action( 'http_api_curl', function( $handle ) { curl_setopt($handle, CURLOPT_CAINFO, ABSPATH . 'certificate.crt'); }); </code></pre> <p>// the value of ABSPATH is: /srv/www/example.co.uk/current/web/wp/</p> <p>Same error remains. Can't tell if the custom cert is being used or not too. If it is then something else must be wrong maybe.</p>
[ { "answer_id": 368584, "author": "Mudasser Mian", "author_id": 189653, "author_profile": "https://wordpress.stackexchange.com/users/189653", "pm_score": 0, "selected": false, "text": "<p>@wharfdale I faced the same problem. All you need to do is to open the file vendor\\automattic\\woocommerce\\src\\WooCommerce\\HttpClient\\Options.php and look for function verifySsl() and replace true with false. The line in the function should look like this after change</p>\n\n<p>return isset($this->options['verify_ssl']) ? (bool) $this->options['verify_ssl'] : false;</p>\n\n<p>This option sets curl options for verifying SSL to false in the woocommerece library and it works!</p>\n" }, { "answer_id": 376130, "author": "Micke Enroos", "author_id": 128071, "author_profile": "https://wordpress.stackexchange.com/users/128071", "pm_score": 1, "selected": false, "text": "<p>You can disable the ssl verification by using <code>'verify_ssl' =&gt; false</code>. So in your code you should change:</p>\n<pre><code>[\n 'wp_api' =&gt; true,\n 'version' =&gt; 'wc/v3',\n 'sslverify' =&gt; false,\n ]\n\n</code></pre>\n<p>to:</p>\n<pre><code> [\n 'wp_api' =&gt; true,\n 'version' =&gt; 'wc/v3',\n 'verify_ssl' =&gt; false,\n ]\n</code></pre>\n<p>Then you don't need to change any source code.</p>\n" } ]
2020/02/29
[ "https://wordpress.stackexchange.com/questions/359766", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52096/" ]
I’ve got a simple php script which is connecting to my wordpress to create a product. Using the woocommerce rest api library. ``` $woocommerce = new Client( 'https://dev.example.co.uk', '123456789', '123456789', [ 'wp_api' => true, 'version' => 'wc/v3', 'sslverify' => false, ] ); // foreach item $woocommerce->post( 'products', $data ); ``` > > Fatal error: Uncaught Automattic\WooCommerce\HttpClient\HttpClientException: cURL Error: SSL certificate problem: self signed certificate in /srv/www/example.co.uk/current/web/app/themes/exampletheme/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php on line 417 > > > I’ve attempted the following: Get the certificate from the dev site: ``` openssl s_client -connect example.co.uk:443 | tee logfile ``` Copied the certificate and made a file from it called **certificate.crt** ``` MIICyTCCAbGgAwIBAgIJANB2.... ``` Uploaded to: ``` /srv/www/example.co.uk/current/web/wp/certificate.crt ``` And now trying to use it to prevent this error. **functions.php** ``` add_action( 'http_api_curl', function( $handle ) { curl_setopt($handle, CURLOPT_CAINFO, ABSPATH . 'certificate.crt'); }); ``` // the value of ABSPATH is: /srv/www/example.co.uk/current/web/wp/ Same error remains. Can't tell if the custom cert is being used or not too. If it is then something else must be wrong maybe.
You can disable the ssl verification by using `'verify_ssl' => false`. So in your code you should change: ``` [ 'wp_api' => true, 'version' => 'wc/v3', 'sslverify' => false, ] ``` to: ``` [ 'wp_api' => true, 'version' => 'wc/v3', 'verify_ssl' => false, ] ``` Then you don't need to change any source code.
359,788
<p>I am trying to add a product with an image via the WooCommerce REST API but getting this error:</p> <blockquote> <p>Fatal error: Uncaught Automattic\WooCommerce\HttpClient\HttpClientException: Error: #0 is an invalid image ID.</p> </blockquote> <p>Despite many other threads similar, no one seems to have an actual answer to why this happens despite the same code in the example of the docs. The image I am trying to use is not already in the media library.</p> <p>The code:</p> <pre><code>$woocommerce = new Client( 'https://www.example.co.uk', '123456789', '123456789', [ 'wp_api' =&gt; true, 'version' =&gt; 'wc/v3', 'sslverify' =&gt; false, ] ); $data = array(); foreach ( $records-&gt;getRecords() as $record ) { $data = [ 'name' =&gt; $record['TITLE'], 'description' =&gt; $record['DESCRIPTION'], 'regular_price' =&gt; $record['PRICE'], 'quantity' =&gt; $record['QUANTITY'], 'images' =&gt; [ 'src' =&gt; 'https://via.placeholder.com/350x150.png', ], ]; $woocommerce-&gt;post( 'products', $data ); } </code></pre> <p>I see nothing wrong. It’s setup in the same way as the example too: <a href="https://woocommerce.github.io/woocommerce-rest-api-docs/?php#create-a-product" rel="nofollow noreferrer">https://woocommerce.github.io/woocommerce-rest-api-docs/?php#create-a-product</a></p>
[ { "answer_id": 368584, "author": "Mudasser Mian", "author_id": 189653, "author_profile": "https://wordpress.stackexchange.com/users/189653", "pm_score": 0, "selected": false, "text": "<p>@wharfdale I faced the same problem. All you need to do is to open the file vendor\\automattic\\woocommerce\\src\\WooCommerce\\HttpClient\\Options.php and look for function verifySsl() and replace true with false. The line in the function should look like this after change</p>\n\n<p>return isset($this->options['verify_ssl']) ? (bool) $this->options['verify_ssl'] : false;</p>\n\n<p>This option sets curl options for verifying SSL to false in the woocommerece library and it works!</p>\n" }, { "answer_id": 376130, "author": "Micke Enroos", "author_id": 128071, "author_profile": "https://wordpress.stackexchange.com/users/128071", "pm_score": 1, "selected": false, "text": "<p>You can disable the ssl verification by using <code>'verify_ssl' =&gt; false</code>. So in your code you should change:</p>\n<pre><code>[\n 'wp_api' =&gt; true,\n 'version' =&gt; 'wc/v3',\n 'sslverify' =&gt; false,\n ]\n\n</code></pre>\n<p>to:</p>\n<pre><code> [\n 'wp_api' =&gt; true,\n 'version' =&gt; 'wc/v3',\n 'verify_ssl' =&gt; false,\n ]\n</code></pre>\n<p>Then you don't need to change any source code.</p>\n" } ]
2020/03/01
[ "https://wordpress.stackexchange.com/questions/359788", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52096/" ]
I am trying to add a product with an image via the WooCommerce REST API but getting this error: > > Fatal error: Uncaught > Automattic\WooCommerce\HttpClient\HttpClientException: Error: #0 is an > invalid image ID. > > > Despite many other threads similar, no one seems to have an actual answer to why this happens despite the same code in the example of the docs. The image I am trying to use is not already in the media library. The code: ``` $woocommerce = new Client( 'https://www.example.co.uk', '123456789', '123456789', [ 'wp_api' => true, 'version' => 'wc/v3', 'sslverify' => false, ] ); $data = array(); foreach ( $records->getRecords() as $record ) { $data = [ 'name' => $record['TITLE'], 'description' => $record['DESCRIPTION'], 'regular_price' => $record['PRICE'], 'quantity' => $record['QUANTITY'], 'images' => [ 'src' => 'https://via.placeholder.com/350x150.png', ], ]; $woocommerce->post( 'products', $data ); } ``` I see nothing wrong. It’s setup in the same way as the example too: <https://woocommerce.github.io/woocommerce-rest-api-docs/?php#create-a-product>
You can disable the ssl verification by using `'verify_ssl' => false`. So in your code you should change: ``` [ 'wp_api' => true, 'version' => 'wc/v3', 'sslverify' => false, ] ``` to: ``` [ 'wp_api' => true, 'version' => 'wc/v3', 'verify_ssl' => false, ] ``` Then you don't need to change any source code.
359,803
<p>I've been going at this issue for hours now, and please save me before i go crazy.....</p> <p>I'm trying to use Wordpress' WP_User_Query to retrieve users from db</p> <p>I've been feeding it with arguments like this, and it works fine...:</p> <pre><code>function getSomeUsers ($year, $month, $day) { $arg = [ 'meta_key' =&gt; 'some_meta_key', 'meta_value' =&gt; 'some_meta_value', 'date_query' =&gt; [ [ 'year' =&gt; $year, 'month' =&gt; $month, 'day' =&gt; $day ] ] ]; $user_query = new WP_User_Query( $arg ); return $user_query; } </code></pre> <p>But when I try to use a meta_query instead, it returns all users in db, and not just the ones that matches the query....</p> <pre><code>function getSomeUsers () { $arg = [ 'meta_query' =&gt; [ [ 'key' =&gt; 'some_meta_key', 'value' =&gt; 'some_meta_value', 'compare' =&gt; '=' ] ] ] ; $user_query = new WP_User_Query( $arg ); return $user_query; } </code></pre> <p>Anybody knows what's wrong?</p> <p>edit: I've tried the meta query on another simple wordpress site, and it works there, so there must be something else going on, meddling with the query..</p> <p>I've been doing some digging with the Query Monitor plugin... I thought it might have been because I've also been meddling with pre_user_query, but I can see that I don't have any actions attached to that hook... so nvm that...</p> <p>but i can see the query being called. This is what it looks like, and as suspected the meta keys in the meta query is not being included:</p> <pre><code>SELECT DISTINCT SQL_CALC_FOUND_ROWS wp_users.* FROM wp_users LEFT JOIN wp_usermeta ON (wp_users.ID = wp_usermeta.user_id AND wp_usermeta.meta_key = 'ur_user_status' ) LEFT JOIN wp_usermeta AS mt1 ON ( wp_users.ID = mt1.user_id ) LEFT JOIN wp_usermeta AS mt2 ON ( wp_users.ID = mt2.user_id ) WHERE 1=1 AND ( ( ( wp_usermeta.user_id IS NULL OR ( mt1.meta_key = 'ur_user_status' AND mt1.meta_value = '1' ) ) AND ( mt2.meta_key = 'wp_3_capabilities' ) ) ) ORDER BY user_login AS </code></pre> <p>It includes some weird user metadata that seems to be added by the User Registration plugin.</p> <p>I deactivated the plugin, and now the meta query works.... huh</p>
[ { "answer_id": 359813, "author": "Siddhesh Shirodkar", "author_id": 163787, "author_profile": "https://wordpress.stackexchange.com/users/163787", "pm_score": 0, "selected": false, "text": "<p>Here is the reference code:</p>\n\n<pre><code>$args = array (\n'role' =&gt; 'reporter',\n'order' =&gt; 'ASC',\n'orderby' =&gt; 'display_name',\n'search' =&gt; '*'.esc_attr( $search_term ).'*',\n'meta_query' =&gt; array(\n 'relation' =&gt; 'OR',\n array(\n 'key' =&gt; 'first_name',\n 'value' =&gt; $search_term,\n 'compare' =&gt; 'LIKE'\n ),\n array(\n 'key' =&gt; 'last_name',\n 'value' =&gt; $search_term,\n 'compare' =&gt; 'LIKE'\n ),\n array(\n 'key' =&gt; 'description',\n 'value' =&gt; $search_term ,\n 'compare' =&gt; 'LIKE'\n )\n )\n);\n\n // Create the WP_User_Query object\n $wp_user_query = new WP_User_Query($args);\n</code></pre>\n" }, { "answer_id": 359918, "author": "Mark Pedersen", "author_id": 183613, "author_profile": "https://wordpress.stackexchange.com/users/183613", "pm_score": 1, "selected": false, "text": "<p>I've tried the meta query on another simple wordpress site, and it works there, so there must be something else going on, meddling with the query..</p>\n\n<p>I've been doing some digging with the Query Monitor plugin... I thought it might have been because I've also been meddling with pre_user_query, but I can see that I don't have any actions attached to that hook... so nvm that...</p>\n\n<p>but i can see the query being called. This is what it looks like, and as suspected the meta keys in the meta query is not being included:</p>\n\n<pre><code>SELECT DISTINCT SQL_CALC_FOUND_ROWS wp_users.*\nFROM wp_users\nLEFT JOIN wp_usermeta\nON (wp_users.ID = wp_usermeta.user_id\nAND wp_usermeta.meta_key = 'ur_user_status' )\nLEFT JOIN wp_usermeta AS mt1\nON ( wp_users.ID = mt1.user_id )\nLEFT JOIN wp_usermeta AS mt2\nON ( wp_users.ID = mt2.user_id )\nWHERE 1=1\nAND ( ( ( wp_usermeta.user_id IS NULL\nOR ( mt1.meta_key = 'ur_user_status'\nAND mt1.meta_value = '1' ) )\nAND ( mt2.meta_key = 'wp_3_capabilities' ) ) )\nORDER BY user_login AS\n</code></pre>\n\n<p>It includes some weird user metadata that seems to be added by the User Registration plugin.</p>\n\n<p>I deactivated the plugin, and now the meta query works.... huh</p>\n" } ]
2020/03/01
[ "https://wordpress.stackexchange.com/questions/359803", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183613/" ]
I've been going at this issue for hours now, and please save me before i go crazy..... I'm trying to use Wordpress' WP\_User\_Query to retrieve users from db I've been feeding it with arguments like this, and it works fine...: ``` function getSomeUsers ($year, $month, $day) { $arg = [ 'meta_key' => 'some_meta_key', 'meta_value' => 'some_meta_value', 'date_query' => [ [ 'year' => $year, 'month' => $month, 'day' => $day ] ] ]; $user_query = new WP_User_Query( $arg ); return $user_query; } ``` But when I try to use a meta\_query instead, it returns all users in db, and not just the ones that matches the query.... ``` function getSomeUsers () { $arg = [ 'meta_query' => [ [ 'key' => 'some_meta_key', 'value' => 'some_meta_value', 'compare' => '=' ] ] ] ; $user_query = new WP_User_Query( $arg ); return $user_query; } ``` Anybody knows what's wrong? edit: I've tried the meta query on another simple wordpress site, and it works there, so there must be something else going on, meddling with the query.. I've been doing some digging with the Query Monitor plugin... I thought it might have been because I've also been meddling with pre\_user\_query, but I can see that I don't have any actions attached to that hook... so nvm that... but i can see the query being called. This is what it looks like, and as suspected the meta keys in the meta query is not being included: ``` SELECT DISTINCT SQL_CALC_FOUND_ROWS wp_users.* FROM wp_users LEFT JOIN wp_usermeta ON (wp_users.ID = wp_usermeta.user_id AND wp_usermeta.meta_key = 'ur_user_status' ) LEFT JOIN wp_usermeta AS mt1 ON ( wp_users.ID = mt1.user_id ) LEFT JOIN wp_usermeta AS mt2 ON ( wp_users.ID = mt2.user_id ) WHERE 1=1 AND ( ( ( wp_usermeta.user_id IS NULL OR ( mt1.meta_key = 'ur_user_status' AND mt1.meta_value = '1' ) ) AND ( mt2.meta_key = 'wp_3_capabilities' ) ) ) ORDER BY user_login AS ``` It includes some weird user metadata that seems to be added by the User Registration plugin. I deactivated the plugin, and now the meta query works.... huh
I've tried the meta query on another simple wordpress site, and it works there, so there must be something else going on, meddling with the query.. I've been doing some digging with the Query Monitor plugin... I thought it might have been because I've also been meddling with pre\_user\_query, but I can see that I don't have any actions attached to that hook... so nvm that... but i can see the query being called. This is what it looks like, and as suspected the meta keys in the meta query is not being included: ``` SELECT DISTINCT SQL_CALC_FOUND_ROWS wp_users.* FROM wp_users LEFT JOIN wp_usermeta ON (wp_users.ID = wp_usermeta.user_id AND wp_usermeta.meta_key = 'ur_user_status' ) LEFT JOIN wp_usermeta AS mt1 ON ( wp_users.ID = mt1.user_id ) LEFT JOIN wp_usermeta AS mt2 ON ( wp_users.ID = mt2.user_id ) WHERE 1=1 AND ( ( ( wp_usermeta.user_id IS NULL OR ( mt1.meta_key = 'ur_user_status' AND mt1.meta_value = '1' ) ) AND ( mt2.meta_key = 'wp_3_capabilities' ) ) ) ORDER BY user_login AS ``` It includes some weird user metadata that seems to be added by the User Registration plugin. I deactivated the plugin, and now the meta query works.... huh
359,887
<p>I want to add jquery plugin to wordpress webpage to provide some animations. I have downloaded "jquery.plate.js" from jqueryscript.net and saved it locally in my custom themes,(js/jquery.plate.js) js folder.</p> <pre><code>&lt;script src="//code.jquery.com/jquery-3.2.1.slim.min.js"&gt;&lt;/script&gt; &lt;script src="jquery.plate.js"&gt;&lt;/script&gt; </code></pre> <ul> <li>I have added the above code in my header using "echo get_template_directory_uri();" function.</li> </ul> <p>not working!</p> <ul> <li><p>tried with adding following code in function.php:</p> <pre><code>function my_extrajs() { ?&gt; &lt;script src="//code.jquery.com/jquery-3.2.1.slim.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="&lt;?php echo get_template_directory_uri(); ?&gt;/js/jquery.plate.js"&gt;&lt;/script&gt; &lt;?php } add_action('wp_head', 'my_extrajs'); </code></pre></li> </ul> <p>Still not working!</p> <ul> <li><p>Tried with adding another code in functions.php:</p> <pre><code>function theme_name_scripts() { wp_enqueue_style( 'style-name', get_stylesheet_uri() ); wp_enqueue_script( 'jquery.plate.js', get_template_directory_uri() . '/js/jquery.plate.js', array('jquery'), '1.0.0', true );} add_action( 'wp_enqueue_scripts', 'theme_name_scripts' ); </code></pre></li> </ul> <p>not working!!</p> <pre><code> $('.text-white.follow').plate(); </code></pre> <p>this code is i used to retrieve jquery animation.for the following element:</p> <pre><code> &lt;div class="col-md-1 col-2 social"&gt; &lt;span class="text-white follow"&gt;&lt;label&gt;FOLLOW&lt;/label&gt;&lt;/span&gt; &lt;span&gt;&lt;a href=""&gt;&lt;img src="&lt;?php echo get_template_directory_uri(); ?&gt;/images/social1.png"&gt;&lt;/a&gt;&lt;/span&gt; &lt;span&gt;&lt;a href=""&gt;&lt;img src="&lt;?php echo get_template_directory_uri(); ?&gt;/images/social2.png"&gt;&lt;/a&gt;&lt;/span&gt; &lt;span&gt;&lt;a href=""&gt;&lt;img src="&lt;?php echo get_template_directory_uri(); ?&gt;/images/social3.png"&gt;&lt;/a&gt;&lt;/span&gt; &lt;/div&gt; </code></pre> <p>Any idea, where i missed??</p> <p>Also,i am beginner in wordpress.Any help would be appreciable.</p>
[ { "answer_id": 359820, "author": "Chipsy", "author_id": 132006, "author_profile": "https://wordpress.stackexchange.com/users/132006", "pm_score": -1, "selected": false, "text": "<p>Kindly check the Error Log file to know the exact error. HTTP 500 error can be due to a lot of things. </p>\n\n<p>Hope you tried with the basic things first -</p>\n\n<ol>\n<li>Disable all the plugins and check.</li>\n<li>Try to switch the theme to the default Twenty20.</li>\n</ol>\n" }, { "answer_id": 359826, "author": "divyaT", "author_id": 177804, "author_profile": "https://wordpress.stackexchange.com/users/177804", "pm_score": 1, "selected": false, "text": "<p>there might be these possibilities please check both the cases</p>\n\n<ul>\n<li>Please allow the debugging mode in your wp-config file\n<code>define('WP_DEBUG', false);</code> make it true. </li>\n<li>If after enabling the debug you didn't get any fatal error, then this\nproblem is related to your hosting server, do check with their\nsupport.</li>\n</ul>\n" } ]
2020/03/03
[ "https://wordpress.stackexchange.com/questions/359887", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/181471/" ]
I want to add jquery plugin to wordpress webpage to provide some animations. I have downloaded "jquery.plate.js" from jqueryscript.net and saved it locally in my custom themes,(js/jquery.plate.js) js folder. ``` <script src="//code.jquery.com/jquery-3.2.1.slim.min.js"></script> <script src="jquery.plate.js"></script> ``` * I have added the above code in my header using "echo get\_template\_directory\_uri();" function. not working! * tried with adding following code in function.php: ``` function my_extrajs() { ?> <script src="//code.jquery.com/jquery-3.2.1.slim.min.js"></script> <script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/jquery.plate.js"></script> <?php } add_action('wp_head', 'my_extrajs'); ``` Still not working! * Tried with adding another code in functions.php: ``` function theme_name_scripts() { wp_enqueue_style( 'style-name', get_stylesheet_uri() ); wp_enqueue_script( 'jquery.plate.js', get_template_directory_uri() . '/js/jquery.plate.js', array('jquery'), '1.0.0', true );} add_action( 'wp_enqueue_scripts', 'theme_name_scripts' ); ``` not working!! ``` $('.text-white.follow').plate(); ``` this code is i used to retrieve jquery animation.for the following element: ``` <div class="col-md-1 col-2 social"> <span class="text-white follow"><label>FOLLOW</label></span> <span><a href=""><img src="<?php echo get_template_directory_uri(); ?>/images/social1.png"></a></span> <span><a href=""><img src="<?php echo get_template_directory_uri(); ?>/images/social2.png"></a></span> <span><a href=""><img src="<?php echo get_template_directory_uri(); ?>/images/social3.png"></a></span> </div> ``` Any idea, where i missed?? Also,i am beginner in wordpress.Any help would be appreciable.
there might be these possibilities please check both the cases * Please allow the debugging mode in your wp-config file `define('WP_DEBUG', false);` make it true. * If after enabling the debug you didn't get any fatal error, then this problem is related to your hosting server, do check with their support.
359,899
<p>I have added the ability for a social security number to be added for users. This field can be edited on the individual users screen but the data is saved to the usermeta table. When editing a new user, I want to check if that number is being used somewhere else for another user as duplicates should not be allowed. </p> <p>My initial code is:</p> <pre><code>function save_cust_user_profile_fields( $user_id ) { if ( isset($_POST['social_number']) ) { update_user_meta( $user_id, 'social_number', intval($_POST['social_number'])); } } add_action( 'personal_options_update', 'save_cust_user_profile_fields' ); add_action( 'edit_user_profile_update', 'save_cust_user_profile_fields' ); </code></pre> <p>But this obviously allows duplicates which it shouldn't.</p>
[ { "answer_id": 359901, "author": "Chetan Vaghela", "author_id": 169856, "author_profile": "https://wordpress.stackexchange.com/users/169856", "pm_score": 2, "selected": true, "text": "<p>You can check duplicate user meta using sql query.in below code if duplicate record found of other users then it will display error message and not update value. add below code in active theme's functions.php file.</p>\n\n<pre><code>function save_cust_user_profile_fields( $user_id ) {\n\n if ( isset($_POST['social_number']) ) {\n global $wpdb;\n $social_number = $_POST['social_number'];\n # query to check duplicate value\n $query = \"SELECT $wpdb-&gt;users.ID FROM $wpdb-&gt;users INNER JOIN $wpdb-&gt;usermeta ON ( $wpdb-&gt;users.ID = $wpdb-&gt;usermeta.user_id ) INNER JOIN $wpdb-&gt;usermeta AS mt1 ON ( $wpdb-&gt;users.ID = mt1.user_id ) WHERE 1=1 AND \n ( $wpdb-&gt;usermeta.meta_key = 'social_number' AND $wpdb-&gt;usermeta.meta_value = $social_number ) \";\n\n $result = $wpdb-&gt;get_results($query);\n #if result found then redirect with error msg\n if($result &amp;&amp; $user_id != $result[0]-&gt;ID){\n add_filter( 'wp_redirect', 'add_notice_query_variable', 99 );\n }\n else\n { \n # if not found duplicate then update\n update_user_meta( $user_id, 'social_number', intval($_POST['social_number'])); \n }\n\n }\n\n}\nadd_action( 'personal_options_update', 'save_cust_user_profile_fields' );\nadd_action( 'edit_user_profile_update', 'save_cust_user_profile_fields' );\n\n#Add query var in url for display error message \nfunction add_notice_query_variable( $location ) {\n remove_filter( 'wp_redirect', 'add_notice_query_variable' , 99 );\n return add_query_arg( array( 'social_number' =&gt; $_POST['social_number'] ), $location );\n}\n\n# display duplicate error admin notice\nadd_action( 'admin_notices', 'admin_notices_callback');\nfunction admin_notices_callback() {\n if ( ! isset( $_GET['social_number'] )) {\n return;\n }\n ?&gt;\n &lt;div class=\"error notice\"&gt;\n &lt;p&gt;&lt;?php esc_html_e( 'social_number : '.$_GET['social_number'].' already used in other user, Please try different!', '' ); ?&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;?php\n }\n</code></pre>\n\n<p>I have tested and it is working fine for me. <a href=\"https://prnt.sc/rau4ug\" rel=\"nofollow noreferrer\">https://prnt.sc/rau4ug</a> let me know if this works for you. </p>\n" }, { "answer_id": 405278, "author": "Piyush", "author_id": 201953, "author_profile": "https://wordpress.stackexchange.com/users/201953", "pm_score": 0, "selected": false, "text": "<p>Can't we do something like this, I just printed the result of above query, it is returning lot of repeated Ids:</p>\n<pre><code>$res = $wpdb-&gt;get_row(&quot;SELECT 1 FROM $wpdb-&gt;usermeta WHERE\n $wpdb-&gt;usermeta.meta_key = 'social_number' AND $wpdb-&gt;usermeta.meta_value = '$social_number' AND $wpdb-&gt;usermeta.user_id != $user-&gt;ID&quot;);\n\nif (!empty($res)) {\n echo &quot;exists&quot;;\n //redirect\n die();\n} else {\n //write your code\n}\n</code></pre>\n" } ]
2020/03/03
[ "https://wordpress.stackexchange.com/questions/359899", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/165412/" ]
I have added the ability for a social security number to be added for users. This field can be edited on the individual users screen but the data is saved to the usermeta table. When editing a new user, I want to check if that number is being used somewhere else for another user as duplicates should not be allowed. My initial code is: ``` function save_cust_user_profile_fields( $user_id ) { if ( isset($_POST['social_number']) ) { update_user_meta( $user_id, 'social_number', intval($_POST['social_number'])); } } add_action( 'personal_options_update', 'save_cust_user_profile_fields' ); add_action( 'edit_user_profile_update', 'save_cust_user_profile_fields' ); ``` But this obviously allows duplicates which it shouldn't.
You can check duplicate user meta using sql query.in below code if duplicate record found of other users then it will display error message and not update value. add below code in active theme's functions.php file. ``` function save_cust_user_profile_fields( $user_id ) { if ( isset($_POST['social_number']) ) { global $wpdb; $social_number = $_POST['social_number']; # query to check duplicate value $query = "SELECT $wpdb->users.ID FROM $wpdb->users INNER JOIN $wpdb->usermeta ON ( $wpdb->users.ID = $wpdb->usermeta.user_id ) INNER JOIN $wpdb->usermeta AS mt1 ON ( $wpdb->users.ID = mt1.user_id ) WHERE 1=1 AND ( $wpdb->usermeta.meta_key = 'social_number' AND $wpdb->usermeta.meta_value = $social_number ) "; $result = $wpdb->get_results($query); #if result found then redirect with error msg if($result && $user_id != $result[0]->ID){ add_filter( 'wp_redirect', 'add_notice_query_variable', 99 ); } else { # if not found duplicate then update update_user_meta( $user_id, 'social_number', intval($_POST['social_number'])); } } } add_action( 'personal_options_update', 'save_cust_user_profile_fields' ); add_action( 'edit_user_profile_update', 'save_cust_user_profile_fields' ); #Add query var in url for display error message function add_notice_query_variable( $location ) { remove_filter( 'wp_redirect', 'add_notice_query_variable' , 99 ); return add_query_arg( array( 'social_number' => $_POST['social_number'] ), $location ); } # display duplicate error admin notice add_action( 'admin_notices', 'admin_notices_callback'); function admin_notices_callback() { if ( ! isset( $_GET['social_number'] )) { return; } ?> <div class="error notice"> <p><?php esc_html_e( 'social_number : '.$_GET['social_number'].' already used in other user, Please try different!', '' ); ?></p> </div> <?php } ``` I have tested and it is working fine for me. <https://prnt.sc/rau4ug> let me know if this works for you.
359,906
<p>when someone send a link of a website in facebook, sometimes it shows the hero image of the website.Like this:<a href="https://i.stack.imgur.com/m4WXg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m4WXg.png" alt="image 1"></a></p> <p>How can i set that for my website?</p>
[ { "answer_id": 359901, "author": "Chetan Vaghela", "author_id": 169856, "author_profile": "https://wordpress.stackexchange.com/users/169856", "pm_score": 2, "selected": true, "text": "<p>You can check duplicate user meta using sql query.in below code if duplicate record found of other users then it will display error message and not update value. add below code in active theme's functions.php file.</p>\n\n<pre><code>function save_cust_user_profile_fields( $user_id ) {\n\n if ( isset($_POST['social_number']) ) {\n global $wpdb;\n $social_number = $_POST['social_number'];\n # query to check duplicate value\n $query = \"SELECT $wpdb-&gt;users.ID FROM $wpdb-&gt;users INNER JOIN $wpdb-&gt;usermeta ON ( $wpdb-&gt;users.ID = $wpdb-&gt;usermeta.user_id ) INNER JOIN $wpdb-&gt;usermeta AS mt1 ON ( $wpdb-&gt;users.ID = mt1.user_id ) WHERE 1=1 AND \n ( $wpdb-&gt;usermeta.meta_key = 'social_number' AND $wpdb-&gt;usermeta.meta_value = $social_number ) \";\n\n $result = $wpdb-&gt;get_results($query);\n #if result found then redirect with error msg\n if($result &amp;&amp; $user_id != $result[0]-&gt;ID){\n add_filter( 'wp_redirect', 'add_notice_query_variable', 99 );\n }\n else\n { \n # if not found duplicate then update\n update_user_meta( $user_id, 'social_number', intval($_POST['social_number'])); \n }\n\n }\n\n}\nadd_action( 'personal_options_update', 'save_cust_user_profile_fields' );\nadd_action( 'edit_user_profile_update', 'save_cust_user_profile_fields' );\n\n#Add query var in url for display error message \nfunction add_notice_query_variable( $location ) {\n remove_filter( 'wp_redirect', 'add_notice_query_variable' , 99 );\n return add_query_arg( array( 'social_number' =&gt; $_POST['social_number'] ), $location );\n}\n\n# display duplicate error admin notice\nadd_action( 'admin_notices', 'admin_notices_callback');\nfunction admin_notices_callback() {\n if ( ! isset( $_GET['social_number'] )) {\n return;\n }\n ?&gt;\n &lt;div class=\"error notice\"&gt;\n &lt;p&gt;&lt;?php esc_html_e( 'social_number : '.$_GET['social_number'].' already used in other user, Please try different!', '' ); ?&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;?php\n }\n</code></pre>\n\n<p>I have tested and it is working fine for me. <a href=\"https://prnt.sc/rau4ug\" rel=\"nofollow noreferrer\">https://prnt.sc/rau4ug</a> let me know if this works for you. </p>\n" }, { "answer_id": 405278, "author": "Piyush", "author_id": 201953, "author_profile": "https://wordpress.stackexchange.com/users/201953", "pm_score": 0, "selected": false, "text": "<p>Can't we do something like this, I just printed the result of above query, it is returning lot of repeated Ids:</p>\n<pre><code>$res = $wpdb-&gt;get_row(&quot;SELECT 1 FROM $wpdb-&gt;usermeta WHERE\n $wpdb-&gt;usermeta.meta_key = 'social_number' AND $wpdb-&gt;usermeta.meta_value = '$social_number' AND $wpdb-&gt;usermeta.user_id != $user-&gt;ID&quot;);\n\nif (!empty($res)) {\n echo &quot;exists&quot;;\n //redirect\n die();\n} else {\n //write your code\n}\n</code></pre>\n" } ]
2020/03/03
[ "https://wordpress.stackexchange.com/questions/359906", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/180966/" ]
when someone send a link of a website in facebook, sometimes it shows the hero image of the website.Like this:[![image 1](https://i.stack.imgur.com/m4WXg.png)](https://i.stack.imgur.com/m4WXg.png) How can i set that for my website?
You can check duplicate user meta using sql query.in below code if duplicate record found of other users then it will display error message and not update value. add below code in active theme's functions.php file. ``` function save_cust_user_profile_fields( $user_id ) { if ( isset($_POST['social_number']) ) { global $wpdb; $social_number = $_POST['social_number']; # query to check duplicate value $query = "SELECT $wpdb->users.ID FROM $wpdb->users INNER JOIN $wpdb->usermeta ON ( $wpdb->users.ID = $wpdb->usermeta.user_id ) INNER JOIN $wpdb->usermeta AS mt1 ON ( $wpdb->users.ID = mt1.user_id ) WHERE 1=1 AND ( $wpdb->usermeta.meta_key = 'social_number' AND $wpdb->usermeta.meta_value = $social_number ) "; $result = $wpdb->get_results($query); #if result found then redirect with error msg if($result && $user_id != $result[0]->ID){ add_filter( 'wp_redirect', 'add_notice_query_variable', 99 ); } else { # if not found duplicate then update update_user_meta( $user_id, 'social_number', intval($_POST['social_number'])); } } } add_action( 'personal_options_update', 'save_cust_user_profile_fields' ); add_action( 'edit_user_profile_update', 'save_cust_user_profile_fields' ); #Add query var in url for display error message function add_notice_query_variable( $location ) { remove_filter( 'wp_redirect', 'add_notice_query_variable' , 99 ); return add_query_arg( array( 'social_number' => $_POST['social_number'] ), $location ); } # display duplicate error admin notice add_action( 'admin_notices', 'admin_notices_callback'); function admin_notices_callback() { if ( ! isset( $_GET['social_number'] )) { return; } ?> <div class="error notice"> <p><?php esc_html_e( 'social_number : '.$_GET['social_number'].' already used in other user, Please try different!', '' ); ?></p> </div> <?php } ``` I have tested and it is working fine for me. <https://prnt.sc/rau4ug> let me know if this works for you.
359,909
<p>I've got a child theme activated and I don't see any head and body in my child theme to place the GTM snippet. </p> <p>How do I do this? I rather not paste in the whole head and body in the child theme to overwrite the parent theme and miss out on updates. </p>
[ { "answer_id": 359901, "author": "Chetan Vaghela", "author_id": 169856, "author_profile": "https://wordpress.stackexchange.com/users/169856", "pm_score": 2, "selected": true, "text": "<p>You can check duplicate user meta using sql query.in below code if duplicate record found of other users then it will display error message and not update value. add below code in active theme's functions.php file.</p>\n\n<pre><code>function save_cust_user_profile_fields( $user_id ) {\n\n if ( isset($_POST['social_number']) ) {\n global $wpdb;\n $social_number = $_POST['social_number'];\n # query to check duplicate value\n $query = \"SELECT $wpdb-&gt;users.ID FROM $wpdb-&gt;users INNER JOIN $wpdb-&gt;usermeta ON ( $wpdb-&gt;users.ID = $wpdb-&gt;usermeta.user_id ) INNER JOIN $wpdb-&gt;usermeta AS mt1 ON ( $wpdb-&gt;users.ID = mt1.user_id ) WHERE 1=1 AND \n ( $wpdb-&gt;usermeta.meta_key = 'social_number' AND $wpdb-&gt;usermeta.meta_value = $social_number ) \";\n\n $result = $wpdb-&gt;get_results($query);\n #if result found then redirect with error msg\n if($result &amp;&amp; $user_id != $result[0]-&gt;ID){\n add_filter( 'wp_redirect', 'add_notice_query_variable', 99 );\n }\n else\n { \n # if not found duplicate then update\n update_user_meta( $user_id, 'social_number', intval($_POST['social_number'])); \n }\n\n }\n\n}\nadd_action( 'personal_options_update', 'save_cust_user_profile_fields' );\nadd_action( 'edit_user_profile_update', 'save_cust_user_profile_fields' );\n\n#Add query var in url for display error message \nfunction add_notice_query_variable( $location ) {\n remove_filter( 'wp_redirect', 'add_notice_query_variable' , 99 );\n return add_query_arg( array( 'social_number' =&gt; $_POST['social_number'] ), $location );\n}\n\n# display duplicate error admin notice\nadd_action( 'admin_notices', 'admin_notices_callback');\nfunction admin_notices_callback() {\n if ( ! isset( $_GET['social_number'] )) {\n return;\n }\n ?&gt;\n &lt;div class=\"error notice\"&gt;\n &lt;p&gt;&lt;?php esc_html_e( 'social_number : '.$_GET['social_number'].' already used in other user, Please try different!', '' ); ?&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;?php\n }\n</code></pre>\n\n<p>I have tested and it is working fine for me. <a href=\"https://prnt.sc/rau4ug\" rel=\"nofollow noreferrer\">https://prnt.sc/rau4ug</a> let me know if this works for you. </p>\n" }, { "answer_id": 405278, "author": "Piyush", "author_id": 201953, "author_profile": "https://wordpress.stackexchange.com/users/201953", "pm_score": 0, "selected": false, "text": "<p>Can't we do something like this, I just printed the result of above query, it is returning lot of repeated Ids:</p>\n<pre><code>$res = $wpdb-&gt;get_row(&quot;SELECT 1 FROM $wpdb-&gt;usermeta WHERE\n $wpdb-&gt;usermeta.meta_key = 'social_number' AND $wpdb-&gt;usermeta.meta_value = '$social_number' AND $wpdb-&gt;usermeta.user_id != $user-&gt;ID&quot;);\n\nif (!empty($res)) {\n echo &quot;exists&quot;;\n //redirect\n die();\n} else {\n //write your code\n}\n</code></pre>\n" } ]
2020/03/03
[ "https://wordpress.stackexchange.com/questions/359909", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183724/" ]
I've got a child theme activated and I don't see any head and body in my child theme to place the GTM snippet. How do I do this? I rather not paste in the whole head and body in the child theme to overwrite the parent theme and miss out on updates.
You can check duplicate user meta using sql query.in below code if duplicate record found of other users then it will display error message and not update value. add below code in active theme's functions.php file. ``` function save_cust_user_profile_fields( $user_id ) { if ( isset($_POST['social_number']) ) { global $wpdb; $social_number = $_POST['social_number']; # query to check duplicate value $query = "SELECT $wpdb->users.ID FROM $wpdb->users INNER JOIN $wpdb->usermeta ON ( $wpdb->users.ID = $wpdb->usermeta.user_id ) INNER JOIN $wpdb->usermeta AS mt1 ON ( $wpdb->users.ID = mt1.user_id ) WHERE 1=1 AND ( $wpdb->usermeta.meta_key = 'social_number' AND $wpdb->usermeta.meta_value = $social_number ) "; $result = $wpdb->get_results($query); #if result found then redirect with error msg if($result && $user_id != $result[0]->ID){ add_filter( 'wp_redirect', 'add_notice_query_variable', 99 ); } else { # if not found duplicate then update update_user_meta( $user_id, 'social_number', intval($_POST['social_number'])); } } } add_action( 'personal_options_update', 'save_cust_user_profile_fields' ); add_action( 'edit_user_profile_update', 'save_cust_user_profile_fields' ); #Add query var in url for display error message function add_notice_query_variable( $location ) { remove_filter( 'wp_redirect', 'add_notice_query_variable' , 99 ); return add_query_arg( array( 'social_number' => $_POST['social_number'] ), $location ); } # display duplicate error admin notice add_action( 'admin_notices', 'admin_notices_callback'); function admin_notices_callback() { if ( ! isset( $_GET['social_number'] )) { return; } ?> <div class="error notice"> <p><?php esc_html_e( 'social_number : '.$_GET['social_number'].' already used in other user, Please try different!', '' ); ?></p> </div> <?php } ``` I have tested and it is working fine for me. <https://prnt.sc/rau4ug> let me know if this works for you.
359,930
<p>In my template i'm using a link for downloading a file (probably a PDF or a JPEG) that I will upload from Media Library. How can I get the url path for this specific file? What template tag I have to use?</p> <p>Thanks</p>
[ { "answer_id": 359901, "author": "Chetan Vaghela", "author_id": 169856, "author_profile": "https://wordpress.stackexchange.com/users/169856", "pm_score": 2, "selected": true, "text": "<p>You can check duplicate user meta using sql query.in below code if duplicate record found of other users then it will display error message and not update value. add below code in active theme's functions.php file.</p>\n\n<pre><code>function save_cust_user_profile_fields( $user_id ) {\n\n if ( isset($_POST['social_number']) ) {\n global $wpdb;\n $social_number = $_POST['social_number'];\n # query to check duplicate value\n $query = \"SELECT $wpdb-&gt;users.ID FROM $wpdb-&gt;users INNER JOIN $wpdb-&gt;usermeta ON ( $wpdb-&gt;users.ID = $wpdb-&gt;usermeta.user_id ) INNER JOIN $wpdb-&gt;usermeta AS mt1 ON ( $wpdb-&gt;users.ID = mt1.user_id ) WHERE 1=1 AND \n ( $wpdb-&gt;usermeta.meta_key = 'social_number' AND $wpdb-&gt;usermeta.meta_value = $social_number ) \";\n\n $result = $wpdb-&gt;get_results($query);\n #if result found then redirect with error msg\n if($result &amp;&amp; $user_id != $result[0]-&gt;ID){\n add_filter( 'wp_redirect', 'add_notice_query_variable', 99 );\n }\n else\n { \n # if not found duplicate then update\n update_user_meta( $user_id, 'social_number', intval($_POST['social_number'])); \n }\n\n }\n\n}\nadd_action( 'personal_options_update', 'save_cust_user_profile_fields' );\nadd_action( 'edit_user_profile_update', 'save_cust_user_profile_fields' );\n\n#Add query var in url for display error message \nfunction add_notice_query_variable( $location ) {\n remove_filter( 'wp_redirect', 'add_notice_query_variable' , 99 );\n return add_query_arg( array( 'social_number' =&gt; $_POST['social_number'] ), $location );\n}\n\n# display duplicate error admin notice\nadd_action( 'admin_notices', 'admin_notices_callback');\nfunction admin_notices_callback() {\n if ( ! isset( $_GET['social_number'] )) {\n return;\n }\n ?&gt;\n &lt;div class=\"error notice\"&gt;\n &lt;p&gt;&lt;?php esc_html_e( 'social_number : '.$_GET['social_number'].' already used in other user, Please try different!', '' ); ?&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;?php\n }\n</code></pre>\n\n<p>I have tested and it is working fine for me. <a href=\"https://prnt.sc/rau4ug\" rel=\"nofollow noreferrer\">https://prnt.sc/rau4ug</a> let me know if this works for you. </p>\n" }, { "answer_id": 405278, "author": "Piyush", "author_id": 201953, "author_profile": "https://wordpress.stackexchange.com/users/201953", "pm_score": 0, "selected": false, "text": "<p>Can't we do something like this, I just printed the result of above query, it is returning lot of repeated Ids:</p>\n<pre><code>$res = $wpdb-&gt;get_row(&quot;SELECT 1 FROM $wpdb-&gt;usermeta WHERE\n $wpdb-&gt;usermeta.meta_key = 'social_number' AND $wpdb-&gt;usermeta.meta_value = '$social_number' AND $wpdb-&gt;usermeta.user_id != $user-&gt;ID&quot;);\n\nif (!empty($res)) {\n echo &quot;exists&quot;;\n //redirect\n die();\n} else {\n //write your code\n}\n</code></pre>\n" } ]
2020/03/03
[ "https://wordpress.stackexchange.com/questions/359930", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70257/" ]
In my template i'm using a link for downloading a file (probably a PDF or a JPEG) that I will upload from Media Library. How can I get the url path for this specific file? What template tag I have to use? Thanks
You can check duplicate user meta using sql query.in below code if duplicate record found of other users then it will display error message and not update value. add below code in active theme's functions.php file. ``` function save_cust_user_profile_fields( $user_id ) { if ( isset($_POST['social_number']) ) { global $wpdb; $social_number = $_POST['social_number']; # query to check duplicate value $query = "SELECT $wpdb->users.ID FROM $wpdb->users INNER JOIN $wpdb->usermeta ON ( $wpdb->users.ID = $wpdb->usermeta.user_id ) INNER JOIN $wpdb->usermeta AS mt1 ON ( $wpdb->users.ID = mt1.user_id ) WHERE 1=1 AND ( $wpdb->usermeta.meta_key = 'social_number' AND $wpdb->usermeta.meta_value = $social_number ) "; $result = $wpdb->get_results($query); #if result found then redirect with error msg if($result && $user_id != $result[0]->ID){ add_filter( 'wp_redirect', 'add_notice_query_variable', 99 ); } else { # if not found duplicate then update update_user_meta( $user_id, 'social_number', intval($_POST['social_number'])); } } } add_action( 'personal_options_update', 'save_cust_user_profile_fields' ); add_action( 'edit_user_profile_update', 'save_cust_user_profile_fields' ); #Add query var in url for display error message function add_notice_query_variable( $location ) { remove_filter( 'wp_redirect', 'add_notice_query_variable' , 99 ); return add_query_arg( array( 'social_number' => $_POST['social_number'] ), $location ); } # display duplicate error admin notice add_action( 'admin_notices', 'admin_notices_callback'); function admin_notices_callback() { if ( ! isset( $_GET['social_number'] )) { return; } ?> <div class="error notice"> <p><?php esc_html_e( 'social_number : '.$_GET['social_number'].' already used in other user, Please try different!', '' ); ?></p> </div> <?php } ``` I have tested and it is working fine for me. <https://prnt.sc/rau4ug> let me know if this works for you.
359,933
<p>I have managed to change the width of the <strong>WordPress block editor</strong> so it uses my max width of my actual theme, making it easier to do layouts during the writing process. Now I wanted to change that to <strong>only</strong> happen when I edit <strong>pages</strong>, <em>not posts</em> or other taxonomies. </p> <p>How do I do that? </p> <p><strong>My current procedure is:</strong></p> <p>Add these lines to my theme´s <strong>functions.php</strong> file:</p> <pre><code>add_theme_support( 'editor-styles' ); add_editor_style( 'style-editor.css' ); </code></pre> <p>Then add this css to my <strong>style-editor.css</strong> file:</p> <pre><code>@media (min-width: 600px) { /* Main column width */ .wp-block { width: 90%; max-width: 1170px; } /* Width of "wide" blocks */ .wp-block[data-align="wide"] { max-width: 1170px; } /* Width of "full-wide" blocks */ .wp-block[data-align="full"] { max-width: none; } } </code></pre> <p>So far so good, the block editor displays the new width, but when I add the filter for making this only on pages, with what I assume is <code>is_page</code>, it does not work and I end up getting the normal wp editor width. Here is the code in <strong>functions.php</strong>:</p> <pre><code>if ( is_page() ) { add_theme_support( 'editor-styles' ); add_editor_style( 'style-editor.css' ); } </code></pre> <p>I guess my problem is that I am using the front-end is_page hook, but I cannot find the wp editor equivalent of that. What is the proper code?</p>
[ { "answer_id": 359934, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 0, "selected": false, "text": "<p>In the admin, if you inspect the body tag you will see WP is adding specific classess, similar to on the frontend. With that said you can use this class to be more specific in your CSS rules.</p>\n\n<p>For example, your code could do this to target when editing pages only ...</p>\n\n<pre><code>@media (min-width: 600px) {\n\n /* Main column width */\n .post-type-page .wp-block { width: 90%; max-width: 1170px; }\n\n /* Width of \"wide\" blocks */\n .post-type-page .wp-block[data-align=\"wide\"] { max-width: 1170px; }\n\n /* Width of \"full-wide\" blocks */\n .post-type-page .wp-block[data-align=\"full\"] { max-width: none; }\n\n}\n</code></pre>\n" }, { "answer_id": 359938, "author": "andiOak", "author_id": 154998, "author_profile": "https://wordpress.stackexchange.com/users/154998", "pm_score": 3, "selected": true, "text": "<p>Because the WordPress hook <code>add_theme_support( 'editor-styles' );</code> adds the css in the style-editor.css and appends the class <code>.editor-styles-wrapper</code> before my <code>.wp-block</code>, the usage of the body classes for page vs. post styles fails. Instead I use the answer from <a href=\"https://davidwalsh.name/add-custom-css-wordpress-admin\" rel=\"nofollow noreferrer\">here, from David Walsh</a>, to add the styles independently to the wp admin area:</p>\n\n<pre><code>// Update CSS within in Admin\nfunction admin_style() {\n wp_enqueue_style('admin-styles', get_template_directory_uri().'/style-editor.css');\n}\nadd_action('admin_enqueue_scripts', 'admin_style');\n</code></pre>\n\n<p>Css code, as answered by @RiddleMeThis, works well now and I can differentiate between the post/page types:</p>\n\n<pre><code>@media (min-width: 600px) {\n\n /* Main column width - pages */\n .post-type-page .wp-block { width: 90%; max-width: 1170px; }\n\n /* Main column width - posts */\n .post-type-post .wp-block { width: 60%; max-width: 800px; }\n\n} \n</code></pre>\n" } ]
2020/03/03
[ "https://wordpress.stackexchange.com/questions/359933", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154998/" ]
I have managed to change the width of the **WordPress block editor** so it uses my max width of my actual theme, making it easier to do layouts during the writing process. Now I wanted to change that to **only** happen when I edit **pages**, *not posts* or other taxonomies. How do I do that? **My current procedure is:** Add these lines to my theme´s **functions.php** file: ``` add_theme_support( 'editor-styles' ); add_editor_style( 'style-editor.css' ); ``` Then add this css to my **style-editor.css** file: ``` @media (min-width: 600px) { /* Main column width */ .wp-block { width: 90%; max-width: 1170px; } /* Width of "wide" blocks */ .wp-block[data-align="wide"] { max-width: 1170px; } /* Width of "full-wide" blocks */ .wp-block[data-align="full"] { max-width: none; } } ``` So far so good, the block editor displays the new width, but when I add the filter for making this only on pages, with what I assume is `is_page`, it does not work and I end up getting the normal wp editor width. Here is the code in **functions.php**: ``` if ( is_page() ) { add_theme_support( 'editor-styles' ); add_editor_style( 'style-editor.css' ); } ``` I guess my problem is that I am using the front-end is\_page hook, but I cannot find the wp editor equivalent of that. What is the proper code?
Because the WordPress hook `add_theme_support( 'editor-styles' );` adds the css in the style-editor.css and appends the class `.editor-styles-wrapper` before my `.wp-block`, the usage of the body classes for page vs. post styles fails. Instead I use the answer from [here, from David Walsh](https://davidwalsh.name/add-custom-css-wordpress-admin), to add the styles independently to the wp admin area: ``` // Update CSS within in Admin function admin_style() { wp_enqueue_style('admin-styles', get_template_directory_uri().'/style-editor.css'); } add_action('admin_enqueue_scripts', 'admin_style'); ``` Css code, as answered by @RiddleMeThis, works well now and I can differentiate between the post/page types: ``` @media (min-width: 600px) { /* Main column width - pages */ .post-type-page .wp-block { width: 90%; max-width: 1170px; } /* Main column width - posts */ .post-type-post .wp-block { width: 60%; max-width: 800px; } } ```
359,972
<p>I've been making a plugin for wordpress that adds two simple text field options. The options are saved successfully in plugin options page but don't work, it doesn't output saved options.</p> <p><a href="https://i.stack.imgur.com/iCvSz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iCvSz.png" alt="enter image description here"></a></p> <p>Here's the code:</p> <pre><code>add_action( 'admin_menu', 'viptips_add_admin_menu' ); add_action( 'admin_init', 'viptips_settings_init' ); function viptips_add_admin_menu( ) { $icon = 'dashicons-editor-table'; add_menu_page( 'VIP Tips', 'VIP Tips', 'manage_options', 'vip_tips', 'viptips_options_page', $icon ); } function viptips_settings_init( ) { register_setting( 'pluginPage', 'viptips_settings' ); add_settings_section( 'viptips_pluginPage_section', __( 'Main plugin options', 'viptips' ), 'viptips_settings_section_callback', 'pluginPage' ); add_settings_field( 'viptips_category_name', __( 'Category name:', 'viptips' ), 'viptips_category_name_render', 'pluginPage', 'viptips_pluginPage_section' ); add_settings_field( 'viptips_postperpage', __( 'Number of posts:', 'viptips' ), 'viptips_postperpage_render', 'pluginPage', 'viptips_pluginPage_section' ); } function viptips_category_name_render( ) { $options = get_option( 'viptips_settings' ); ?&gt; &lt;input type='text' name='viptips_settings[viptips_category_name]' value='&lt;?php echo $options['viptips_category_name']; ?&gt;'&gt; &lt;p class="description" id="tagline-description"&gt;Name of the category that contains predictions&lt;/p&gt; &lt;?php } function viptips_postperpage_render( ) { $options = get_option( 'viptips_settings' ); ?&gt; &lt;input type='number' name='viptips_settings[viptips_postperpage]' value='&lt;?php echo $options['viptips_postperpage']; ?&gt;'&gt; &lt;p class="description" id="tagline-description"&gt;Number of posts to be displayed in table.&lt;/p&gt; &lt;?php } function viptips_settings_section_callback( ) { echo __( 'Don\'t forget to use the &lt;strong&gt;[tabscat]&lt;/strong&gt; shortcode, in the page you want the tips table to be displayed!*', 'viptips' ); } function viptips_options_page( ) { ?&gt; &lt;form action='options.php' method='post'&gt; &lt;h1&gt;VIP Tips&lt;/h1&gt; &lt;?php settings_fields( 'pluginPage' ); do_settings_sections( 'pluginPage' ); submit_button(); ?&gt; &lt;/form&gt; &lt;?php } </code></pre> <p>To output saved options, I use:</p> <pre><code>$category_name = get_option('viptips_category_name'); $postperpage = get_option('viptips_postperpage'); $args = array( 'post_type' =&gt; 'post', 'post_status' =&gt; 'publish', 'category_name' =&gt; $category_name, 'post_per_page' =&gt; $postperpage ); </code></pre> <p>Where did I go wrong?</p>
[ { "answer_id": 359934, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 0, "selected": false, "text": "<p>In the admin, if you inspect the body tag you will see WP is adding specific classess, similar to on the frontend. With that said you can use this class to be more specific in your CSS rules.</p>\n\n<p>For example, your code could do this to target when editing pages only ...</p>\n\n<pre><code>@media (min-width: 600px) {\n\n /* Main column width */\n .post-type-page .wp-block { width: 90%; max-width: 1170px; }\n\n /* Width of \"wide\" blocks */\n .post-type-page .wp-block[data-align=\"wide\"] { max-width: 1170px; }\n\n /* Width of \"full-wide\" blocks */\n .post-type-page .wp-block[data-align=\"full\"] { max-width: none; }\n\n}\n</code></pre>\n" }, { "answer_id": 359938, "author": "andiOak", "author_id": 154998, "author_profile": "https://wordpress.stackexchange.com/users/154998", "pm_score": 3, "selected": true, "text": "<p>Because the WordPress hook <code>add_theme_support( 'editor-styles' );</code> adds the css in the style-editor.css and appends the class <code>.editor-styles-wrapper</code> before my <code>.wp-block</code>, the usage of the body classes for page vs. post styles fails. Instead I use the answer from <a href=\"https://davidwalsh.name/add-custom-css-wordpress-admin\" rel=\"nofollow noreferrer\">here, from David Walsh</a>, to add the styles independently to the wp admin area:</p>\n\n<pre><code>// Update CSS within in Admin\nfunction admin_style() {\n wp_enqueue_style('admin-styles', get_template_directory_uri().'/style-editor.css');\n}\nadd_action('admin_enqueue_scripts', 'admin_style');\n</code></pre>\n\n<p>Css code, as answered by @RiddleMeThis, works well now and I can differentiate between the post/page types:</p>\n\n<pre><code>@media (min-width: 600px) {\n\n /* Main column width - pages */\n .post-type-page .wp-block { width: 90%; max-width: 1170px; }\n\n /* Main column width - posts */\n .post-type-post .wp-block { width: 60%; max-width: 800px; }\n\n} \n</code></pre>\n" } ]
2020/03/04
[ "https://wordpress.stackexchange.com/questions/359972", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33903/" ]
I've been making a plugin for wordpress that adds two simple text field options. The options are saved successfully in plugin options page but don't work, it doesn't output saved options. [![enter image description here](https://i.stack.imgur.com/iCvSz.png)](https://i.stack.imgur.com/iCvSz.png) Here's the code: ``` add_action( 'admin_menu', 'viptips_add_admin_menu' ); add_action( 'admin_init', 'viptips_settings_init' ); function viptips_add_admin_menu( ) { $icon = 'dashicons-editor-table'; add_menu_page( 'VIP Tips', 'VIP Tips', 'manage_options', 'vip_tips', 'viptips_options_page', $icon ); } function viptips_settings_init( ) { register_setting( 'pluginPage', 'viptips_settings' ); add_settings_section( 'viptips_pluginPage_section', __( 'Main plugin options', 'viptips' ), 'viptips_settings_section_callback', 'pluginPage' ); add_settings_field( 'viptips_category_name', __( 'Category name:', 'viptips' ), 'viptips_category_name_render', 'pluginPage', 'viptips_pluginPage_section' ); add_settings_field( 'viptips_postperpage', __( 'Number of posts:', 'viptips' ), 'viptips_postperpage_render', 'pluginPage', 'viptips_pluginPage_section' ); } function viptips_category_name_render( ) { $options = get_option( 'viptips_settings' ); ?> <input type='text' name='viptips_settings[viptips_category_name]' value='<?php echo $options['viptips_category_name']; ?>'> <p class="description" id="tagline-description">Name of the category that contains predictions</p> <?php } function viptips_postperpage_render( ) { $options = get_option( 'viptips_settings' ); ?> <input type='number' name='viptips_settings[viptips_postperpage]' value='<?php echo $options['viptips_postperpage']; ?>'> <p class="description" id="tagline-description">Number of posts to be displayed in table.</p> <?php } function viptips_settings_section_callback( ) { echo __( 'Don\'t forget to use the <strong>[tabscat]</strong> shortcode, in the page you want the tips table to be displayed!*', 'viptips' ); } function viptips_options_page( ) { ?> <form action='options.php' method='post'> <h1>VIP Tips</h1> <?php settings_fields( 'pluginPage' ); do_settings_sections( 'pluginPage' ); submit_button(); ?> </form> <?php } ``` To output saved options, I use: ``` $category_name = get_option('viptips_category_name'); $postperpage = get_option('viptips_postperpage'); $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'category_name' => $category_name, 'post_per_page' => $postperpage ); ``` Where did I go wrong?
Because the WordPress hook `add_theme_support( 'editor-styles' );` adds the css in the style-editor.css and appends the class `.editor-styles-wrapper` before my `.wp-block`, the usage of the body classes for page vs. post styles fails. Instead I use the answer from [here, from David Walsh](https://davidwalsh.name/add-custom-css-wordpress-admin), to add the styles independently to the wp admin area: ``` // Update CSS within in Admin function admin_style() { wp_enqueue_style('admin-styles', get_template_directory_uri().'/style-editor.css'); } add_action('admin_enqueue_scripts', 'admin_style'); ``` Css code, as answered by @RiddleMeThis, works well now and I can differentiate between the post/page types: ``` @media (min-width: 600px) { /* Main column width - pages */ .post-type-page .wp-block { width: 90%; max-width: 1170px; } /* Main column width - posts */ .post-type-post .wp-block { width: 60%; max-width: 800px; } } ```
359,988
<p>Private posts are visible only to administrators and editors, but I have found that they are displayed publicly in RSS feeds. How can I remove them from there?</p> <p>I have this code but it doesn't work:</p> <pre><code>function removeRssPrivatePost($content) { global $post; if ($post-&gt;post_status == 'private') { return; } return $content; } add_filter('the_excerpt_rss', 'removeRssPrivatePost'); add_filter('the_content_feed', 'removeRssPrivatePost'); </code></pre>
[ { "answer_id": 359934, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 0, "selected": false, "text": "<p>In the admin, if you inspect the body tag you will see WP is adding specific classess, similar to on the frontend. With that said you can use this class to be more specific in your CSS rules.</p>\n\n<p>For example, your code could do this to target when editing pages only ...</p>\n\n<pre><code>@media (min-width: 600px) {\n\n /* Main column width */\n .post-type-page .wp-block { width: 90%; max-width: 1170px; }\n\n /* Width of \"wide\" blocks */\n .post-type-page .wp-block[data-align=\"wide\"] { max-width: 1170px; }\n\n /* Width of \"full-wide\" blocks */\n .post-type-page .wp-block[data-align=\"full\"] { max-width: none; }\n\n}\n</code></pre>\n" }, { "answer_id": 359938, "author": "andiOak", "author_id": 154998, "author_profile": "https://wordpress.stackexchange.com/users/154998", "pm_score": 3, "selected": true, "text": "<p>Because the WordPress hook <code>add_theme_support( 'editor-styles' );</code> adds the css in the style-editor.css and appends the class <code>.editor-styles-wrapper</code> before my <code>.wp-block</code>, the usage of the body classes for page vs. post styles fails. Instead I use the answer from <a href=\"https://davidwalsh.name/add-custom-css-wordpress-admin\" rel=\"nofollow noreferrer\">here, from David Walsh</a>, to add the styles independently to the wp admin area:</p>\n\n<pre><code>// Update CSS within in Admin\nfunction admin_style() {\n wp_enqueue_style('admin-styles', get_template_directory_uri().'/style-editor.css');\n}\nadd_action('admin_enqueue_scripts', 'admin_style');\n</code></pre>\n\n<p>Css code, as answered by @RiddleMeThis, works well now and I can differentiate between the post/page types:</p>\n\n<pre><code>@media (min-width: 600px) {\n\n /* Main column width - pages */\n .post-type-page .wp-block { width: 90%; max-width: 1170px; }\n\n /* Main column width - posts */\n .post-type-post .wp-block { width: 60%; max-width: 800px; }\n\n} \n</code></pre>\n" } ]
2020/03/04
[ "https://wordpress.stackexchange.com/questions/359988", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/174158/" ]
Private posts are visible only to administrators and editors, but I have found that they are displayed publicly in RSS feeds. How can I remove them from there? I have this code but it doesn't work: ``` function removeRssPrivatePost($content) { global $post; if ($post->post_status == 'private') { return; } return $content; } add_filter('the_excerpt_rss', 'removeRssPrivatePost'); add_filter('the_content_feed', 'removeRssPrivatePost'); ```
Because the WordPress hook `add_theme_support( 'editor-styles' );` adds the css in the style-editor.css and appends the class `.editor-styles-wrapper` before my `.wp-block`, the usage of the body classes for page vs. post styles fails. Instead I use the answer from [here, from David Walsh](https://davidwalsh.name/add-custom-css-wordpress-admin), to add the styles independently to the wp admin area: ``` // Update CSS within in Admin function admin_style() { wp_enqueue_style('admin-styles', get_template_directory_uri().'/style-editor.css'); } add_action('admin_enqueue_scripts', 'admin_style'); ``` Css code, as answered by @RiddleMeThis, works well now and I can differentiate between the post/page types: ``` @media (min-width: 600px) { /* Main column width - pages */ .post-type-page .wp-block { width: 90%; max-width: 1170px; } /* Main column width - posts */ .post-type-post .wp-block { width: 60%; max-width: 800px; } } ```
360,052
<p>I try, when click the submit button then pass the ajax request with some values then calculate that values and return.</p> <p><strong>My Problem</strong> : when I make custom Ajax Call then I get 400 error from admin-ajax.php. Please help me to find my mistake or best way to do this.</p> <p><strong>Ajax Call - footer.php(theme footer)</strong></p> <pre><code> &lt;script&gt; $(function() { $("#calc_form").on("submit", function(e) { // alert("submit"); e.preventDefault(); $.ajax({ method: "POST", url: "/wp-admin/admin-ajax.php", data: { action: 'calculation', message_id: $('#tot_tax_three_month_Input').val() }, dataType: 'json', success: function (output) { } }); }); }); &lt;/script&gt; </code></pre> <p><strong>Admin-ajax.php</strong></p> <pre><code>// handle the ajax request function calculation() { $value = $_REQUEST['message_id']; echo json_encode(array("value" =&gt; $value)); die(); } // register the ajax action for authenticated users add_action('wp_ajax_calculation', 'calculation'); // register the ajax action for unauthenticated users add_action('wp_ajax_nopriv_calculation', 'calculation'); </code></pre> <p><strong>test.php</strong></p> <pre><code> &lt;form id="calc_form"&gt; &lt;table class="table"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th style="width: 40%" scope="col"&gt;&lt;/th&gt; &lt;th scope="col"&gt;Per month LKR&lt;/th&gt; &lt;th scope="col"&gt;For 3 months period* LKR&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td colspan="2" class=" text-danger"&gt;&lt;b&gt;Tax amount for 3 months&lt;/b&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="" id="tot_tax_three_month_Input" class="form-control " /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="2"&gt;&lt;/td&gt; &lt;td&gt; &lt;button type="submit" id="btnCalculate" class="btn btn-success"&gt;Calculate&lt;/button&gt; &lt;button type="button" id="btnReset" class="btn btn-secondary"&gt;Reset&lt;/button&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/form&gt; </code></pre>
[ { "answer_id": 360019, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 0, "selected": false, "text": "<p>If you create and activate a child theme you will not lose any pages or posts.</p>\n\n<p>BUT, depending on your theme and how its setup, if the theme uses custom theme options, you may need to re-enter those in your child theme.</p>\n\n<p>For example, settings inside of the Appearance > Customize will not carry over to your child theme.</p>\n\n<p>If the site is already in production it would be best to setup a staging or test environment so you can create and test out your child theme before activating it on production. </p>\n" }, { "answer_id": 360020, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 2, "selected": false, "text": "<p>Your content is stored in the database, not in the theme. If you switch themes or use a child theme, the content is still there.</p>\n\n<p>Also, if you run a child theme, the parent theme is still in use: Any modifications from it that you don't overwrite are still executed.</p>\n" } ]
2020/03/05
[ "https://wordpress.stackexchange.com/questions/360052", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152021/" ]
I try, when click the submit button then pass the ajax request with some values then calculate that values and return. **My Problem** : when I make custom Ajax Call then I get 400 error from admin-ajax.php. Please help me to find my mistake or best way to do this. **Ajax Call - footer.php(theme footer)** ``` <script> $(function() { $("#calc_form").on("submit", function(e) { // alert("submit"); e.preventDefault(); $.ajax({ method: "POST", url: "/wp-admin/admin-ajax.php", data: { action: 'calculation', message_id: $('#tot_tax_three_month_Input').val() }, dataType: 'json', success: function (output) { } }); }); }); </script> ``` **Admin-ajax.php** ``` // handle the ajax request function calculation() { $value = $_REQUEST['message_id']; echo json_encode(array("value" => $value)); die(); } // register the ajax action for authenticated users add_action('wp_ajax_calculation', 'calculation'); // register the ajax action for unauthenticated users add_action('wp_ajax_nopriv_calculation', 'calculation'); ``` **test.php** ``` <form id="calc_form"> <table class="table"> <thead> <tr> <th style="width: 40%" scope="col"></th> <th scope="col">Per month LKR</th> <th scope="col">For 3 months period* LKR</th> </tr> </thead> <tbody> <tr> <td colspan="2" class=" text-danger"><b>Tax amount for 3 months</b></td> <td><input type="text" name="" id="tot_tax_three_month_Input" class="form-control " /></td> </tr> <tr> <td colspan="2"></td> <td> <button type="submit" id="btnCalculate" class="btn btn-success">Calculate</button> <button type="button" id="btnReset" class="btn btn-secondary">Reset</button> </td> </tr> </tbody> </table> </form> ```
Your content is stored in the database, not in the theme. If you switch themes or use a child theme, the content is still there. Also, if you run a child theme, the parent theme is still in use: Any modifications from it that you don't overwrite are still executed.
360,077
<p>I am new to wordpress development, I am leaning how to make a theme from scratch. I don't want to use any plugin to achieve this. </p> <p>How to create first post/ fifth post/ ninth post full width, rest in three columns and so on.</p> <p>I tried this but first post is not repeating</p> <pre><code> &lt;?php get_header() ?&gt; &lt;div class="container-fluid"&gt; &lt;div class="row"&gt; &lt;?php $i = 0; while ( have_posts() ) : the_post(); ?&gt; &lt;?php if ($i++ == 0) : ?&gt; &lt;div class="col-sm-12 blog"&gt; &lt;div class="row"&gt; &lt;div class="col-sm-8 p-0"&gt; &lt;?php the_post_thumbnail()?&gt; &lt;/div&gt; &lt;div class="col-sm-4 align-self-center"&gt; &lt;div&gt;&lt;h3&gt;&lt;?php the_title()?&gt;&lt;/h3&gt;&lt;/div&gt; &lt;div&gt;&lt;?php the_excerpt()?&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php else: ?&gt; &lt;div class="col-sm-4 blog py-3"&gt; &lt;?php the_post_thumbnail()?&gt; &lt;div&gt;&lt;h3&gt;&lt;?php the_title()?&gt;&lt;/h3&gt;&lt;/div&gt; &lt;div&gt;&lt;?php the_excerpt()?&gt;&lt;/div&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;?php endwhile ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php get_footer() ?&gt; </code></pre> <p><a href="https://i.stack.imgur.com/fn3j9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fn3j9.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 360069, "author": "TomC", "author_id": 36980, "author_profile": "https://wordpress.stackexchange.com/users/36980", "pm_score": 0, "selected": false, "text": "<p>Then do it as a plugin and then use <code>include();</code> to organise your PHP custom functions in their own PHP files either within the plugin directory or outside of it.</p>\n\n<p>Also, you should consider using it as a <a href=\"https://wordpress.org/support/article/must-use-plugins/\" rel=\"nofollow noreferrer\">Must Use plugin</a> if the site heavily relies on the functions.</p>\n" }, { "answer_id": 360103, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 2, "selected": true, "text": "<p>Since you want to be able to use these functions within your themes AND plugins, and taking into consideration your comment regarding loading, I'd recommend the following approach.</p>\n\n<p>Organize your functions into a library - depending on your methods and approaches, this could be multiple or single files. It could be just functions or as a class.</p>\n\n<p>Wrap your functions or classes with conditional checks to make sure they are not defined already (in case you inadvertently load it twice). <code>if ( function_exists( ...</code> or <code>if ( class_exists( ...</code></p>\n\n<p>Establish one point in your plugin or theme where you check if a key function or class exists, and if not, use <code>include_once()</code> to load your library file. Hook this to the initialization of your plugin or theme, so that you're just doing it once (although each theme or plugin would check - but if it's already loaded, it will only be loaded once). For example:</p>\n\n<p><code>if ( ! function_exists( 'my_cool_utility' ) ) {\n include_once( 'my_function_library.php' );\n}</code></p>\n\n<p>Doing it this way allows you to use your library across multiple themes and plugins that may or may not be used together, while making sure (1) that the code is there and available while (2) avoiding issues of it being loaded more than once.</p>\n\n<p>This is a method that I personally use in developing both free and premium plugins and themes. I have a number of libraries that get reused across different products that may or may not be used together. By packaging the library with the theme or plugin, I know it will be there and the user doesn't have to load something separate to use it.</p>\n\n<p>Hope I explained that well enough for you. If not, ask questions in the comments and I'll try to edit for clarity.</p>\n" }, { "answer_id": 365046, "author": "Tim", "author_id": 113538, "author_profile": "https://wordpress.stackexchange.com/users/113538", "pm_score": 0, "selected": false, "text": "<p>Here is my final solution. Credits to @butlerblog for the hint.</p>\n\n<p>I created a component package that I can include on every website (and update with new functionnalities anytime).</p>\n\n<p>Here is the <code>composer.json</code> file.</p>\n\n<pre><code> {\n \"name\": \"tim/wp-utils\",\n \"description\": \"WordPress utility functions\",\n \"type\": \"component\",\n \"version\": \"1.0.2\",\n \"authors\": [\n {\n \"name\": \"Timothée Moulin\",\n \"email\": \"[email protected]\"\n }\n ],\n \"require\": {\n \"php\": \"&gt;=7.3\",\n \"robloach/component-installer\": \"*\"\n },\n \"extra\": {\n \"component\": {\n \"files\": [\n \"*\"\n ]\n }\n }\n }\n</code></pre>\n\n<p>Notice the <code>robloach/component-installer</code> requirement and the <code>extra component</code> configuration.\nThis allows me to place the \"plugin\" anywhere logical for me in my app (instead of the vendor directory).</p>\n\n<p>And in my plugin file I surrounded every function declaration with a <code>function_exists</code> check</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\nif (!function_exists('my_utility_function')) {\n function my_utility_function() {\n // @todo\n }\n}\n</code></pre>\n\n<p>Then in every plugin <code>plugin.php</code> and theme <code>functions.php</code> file I include the utility file </p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php require_once WP_CONTENT_DIR . '/components/wp-utils/wp-utils.php';\n</code></pre>\n" } ]
2020/03/05
[ "https://wordpress.stackexchange.com/questions/360077", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183839/" ]
I am new to wordpress development, I am leaning how to make a theme from scratch. I don't want to use any plugin to achieve this. How to create first post/ fifth post/ ninth post full width, rest in three columns and so on. I tried this but first post is not repeating ``` <?php get_header() ?> <div class="container-fluid"> <div class="row"> <?php $i = 0; while ( have_posts() ) : the_post(); ?> <?php if ($i++ == 0) : ?> <div class="col-sm-12 blog"> <div class="row"> <div class="col-sm-8 p-0"> <?php the_post_thumbnail()?> </div> <div class="col-sm-4 align-self-center"> <div><h3><?php the_title()?></h3></div> <div><?php the_excerpt()?></div> </div> </div> </div> <?php else: ?> <div class="col-sm-4 blog py-3"> <?php the_post_thumbnail()?> <div><h3><?php the_title()?></h3></div> <div><?php the_excerpt()?></div> </div> <?php endif; ?> <?php endwhile ?> </div> </div> <?php get_footer() ?> ``` [![enter image description here](https://i.stack.imgur.com/fn3j9.jpg)](https://i.stack.imgur.com/fn3j9.jpg)
Since you want to be able to use these functions within your themes AND plugins, and taking into consideration your comment regarding loading, I'd recommend the following approach. Organize your functions into a library - depending on your methods and approaches, this could be multiple or single files. It could be just functions or as a class. Wrap your functions or classes with conditional checks to make sure they are not defined already (in case you inadvertently load it twice). `if ( function_exists( ...` or `if ( class_exists( ...` Establish one point in your plugin or theme where you check if a key function or class exists, and if not, use `include_once()` to load your library file. Hook this to the initialization of your plugin or theme, so that you're just doing it once (although each theme or plugin would check - but if it's already loaded, it will only be loaded once). For example: `if ( ! function_exists( 'my_cool_utility' ) ) { include_once( 'my_function_library.php' ); }` Doing it this way allows you to use your library across multiple themes and plugins that may or may not be used together, while making sure (1) that the code is there and available while (2) avoiding issues of it being loaded more than once. This is a method that I personally use in developing both free and premium plugins and themes. I have a number of libraries that get reused across different products that may or may not be used together. By packaging the library with the theme or plugin, I know it will be there and the user doesn't have to load something separate to use it. Hope I explained that well enough for you. If not, ask questions in the comments and I'll try to edit for clarity.
360,088
<p>I have created the custom taxonomy for categories. I want to list the child categories lists of current parent category in child page.</p> <pre><code>$cateID = get_queried_object_id(); $args = array( 'format' =&gt; 'name', 'separator' =&gt; ' ', 'link' =&gt; false, 'inclusive' =&gt; true ); $checkparent = get_term_parents_list( $cateID, 'my-taxonamy' , $args ); </code></pre> <p>I have tried the above code. But the code returns the parent category name/link. Any way to get the parent category id in child category page? Any methods or hooks are there in wordpress for getting the parent category id?</p> <p>Example case:</p> <ol> <li>Parent category1 <ul> <li>Child category1</li> <li>Child category1</li> <li>Child category3</li> </ul></li> <li>Parent category1 <ul> <li>Child category1</li> <li>Child category1</li> </ul></li> </ol> <p>If i am in <strong>child category1</strong> page, want to list the below categories.</p> <ul> <li>Child category1</li> <li>Child category1</li> <li>Child category3</li> </ul> <p>Problem: I cannot able to get the parent category id from the child category. </p> <p>Thanks in advance ;)</p>
[ { "answer_id": 360128, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<p>On a taxonomy archive page, be it for a child or parent term, you can get the current/<em>queried</em> term object/data using <a href=\"https://developer.wordpress.org/reference/functions/get_queried_object/\" rel=\"nofollow noreferrer\"><code>get_queried_object()</code></a> which contains properties like <code>term_id</code> (the term ID) and <code>slug</code> (the term slug). And the property name for the ID of the parent term is <code>parent</code>. So you can do so to get the parent's term ID:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$cat = get_queried_object();\n$parent_cat_id = $cat-&gt;parent;\n</code></pre>\n\n<p>And for displaying a list of terms in the parent term, you can use <a href=\"https://developer.wordpress.org/reference/functions/wp_list_categories/\" rel=\"nofollow noreferrer\"><code>wp_list_categories()</code></a>. Here's an example with the <code>title_li</code> set to <code>''</code> and <code>echo</code> set to <code>0</code>, which means I'm manually putting the output into an <code>UL</code> (<code>&lt;ul&gt;&lt;/ul&gt;</code>):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$cat = get_queried_object();\n\n$list = wp_list_categories( [\n 'taxonomy' =&gt; $cat-&gt;taxonomy,\n 'child_of' =&gt; $cat-&gt;parent,\n 'title_li' =&gt; '',\n 'echo' =&gt; 0,\n] );\n\nif ( $list ) {\n echo \"&lt;ul&gt;$list&lt;/ul&gt;\";\n}\n</code></pre>\n\n<p>If you want <em>full control</em> over the HTML, e.g. to add custom HTML before/after the term link or perhaps to add custom CSS classes, you can use <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\"><code>get_terms()</code></a> and loop through the term objects to display the term:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$cat = get_queried_object();\n\n$cats = get_terms( [\n 'taxonomy' =&gt; $cat-&gt;taxonomy,\n 'child_of' =&gt; $cat-&gt;parent,\n] );\n\nif ( ! empty( $cats ) ) {\n echo '&lt;ul&gt;';\n foreach ( $cats as $cat ) {\n $url = esc_url( get_category_link( $cat ) );\n // change the 'before' and/or 'after' or whatever necessary\n echo \"&lt;li&gt;before &lt;a href='$url'&gt;$cat-&gt;name&lt;/a&gt; after&lt;/li&gt;\";\n }\n echo '&lt;/ul&gt;';\n}\n</code></pre>\n" }, { "answer_id": 360130, "author": "HK89", "author_id": 179278, "author_profile": "https://wordpress.stackexchange.com/users/179278", "pm_score": 0, "selected": false, "text": "<p>Using a get_term function is Retrieve the terms in a given taxonomy or list of taxonomies.</p>\n\n<p>Refer this Link : <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_terms/</a></p>\n\n<pre><code> /*change on 'taxonomy'=&gt; 'your texonomy name'*/\n $terms = get_terms(array('taxonomy'=&gt; 'category','hide_empty' =&gt; false, )); ?&gt;\n &lt;div class=\"category_all\"&gt;\n &lt;div class=\"categor\"&gt;\n &lt;?php \n echo \"&lt;ol&gt;\";\n //get parent category term id $term-&gt;term_id \n foreach ( $terms as $term ) {\n if ($term-&gt;parent == 0 ) {\n echo \"&lt;li&gt;\"; \n echo $term-&gt;name; // Parent Category Name \n echo \"&lt;ul&gt;\";\n $subterms = get_terms(array('taxonomy'=&gt; 'category','hide_empty' =&gt; false,'parent'=&gt; $term-&gt;term_id));\n\n //get child category term id $value-&gt;term_id\n foreach ($subterms as $key =&gt; $value) \n {\n echo \"&lt;li&gt;\".$value-&gt;name.\"&lt;/li&gt;\"; // Child Category Name \n }\n echo \"&lt;/ul&gt;\"; \n echo \"&lt;/li&gt;\";\n } \n\n }\n echo \"&lt;/ol&gt;\";\n ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n&lt;?php\n</code></pre>\n\n<p>If you want to get category term id then you can use $term->term_id in your expression</p>\n\n<p>Screenshot of parent with child Category </p>\n\n<p><a href=\"https://i.stack.imgur.com/G5Fmr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/G5Fmr.png\" alt=\"enter image description here\"></a></p>\n" } ]
2020/03/05
[ "https://wordpress.stackexchange.com/questions/360088", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/163406/" ]
I have created the custom taxonomy for categories. I want to list the child categories lists of current parent category in child page. ``` $cateID = get_queried_object_id(); $args = array( 'format' => 'name', 'separator' => ' ', 'link' => false, 'inclusive' => true ); $checkparent = get_term_parents_list( $cateID, 'my-taxonamy' , $args ); ``` I have tried the above code. But the code returns the parent category name/link. Any way to get the parent category id in child category page? Any methods or hooks are there in wordpress for getting the parent category id? Example case: 1. Parent category1 * Child category1 * Child category1 * Child category3 2. Parent category1 * Child category1 * Child category1 If i am in **child category1** page, want to list the below categories. * Child category1 * Child category1 * Child category3 Problem: I cannot able to get the parent category id from the child category. Thanks in advance ;)
On a taxonomy archive page, be it for a child or parent term, you can get the current/*queried* term object/data using [`get_queried_object()`](https://developer.wordpress.org/reference/functions/get_queried_object/) which contains properties like `term_id` (the term ID) and `slug` (the term slug). And the property name for the ID of the parent term is `parent`. So you can do so to get the parent's term ID: ```php $cat = get_queried_object(); $parent_cat_id = $cat->parent; ``` And for displaying a list of terms in the parent term, you can use [`wp_list_categories()`](https://developer.wordpress.org/reference/functions/wp_list_categories/). Here's an example with the `title_li` set to `''` and `echo` set to `0`, which means I'm manually putting the output into an `UL` (`<ul></ul>`): ```php $cat = get_queried_object(); $list = wp_list_categories( [ 'taxonomy' => $cat->taxonomy, 'child_of' => $cat->parent, 'title_li' => '', 'echo' => 0, ] ); if ( $list ) { echo "<ul>$list</ul>"; } ``` If you want *full control* over the HTML, e.g. to add custom HTML before/after the term link or perhaps to add custom CSS classes, you can use [`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/) and loop through the term objects to display the term: ```php $cat = get_queried_object(); $cats = get_terms( [ 'taxonomy' => $cat->taxonomy, 'child_of' => $cat->parent, ] ); if ( ! empty( $cats ) ) { echo '<ul>'; foreach ( $cats as $cat ) { $url = esc_url( get_category_link( $cat ) ); // change the 'before' and/or 'after' or whatever necessary echo "<li>before <a href='$url'>$cat->name</a> after</li>"; } echo '</ul>'; } ```
360,145
<p>I used a theme, which created a custom type. Now I want to change the theme, but when I disable the theme, the custom type is also disabled. I tried using CPT plugin, and re-create the custom type, but it tells me that the custom type is already present and it can't recreate it.</p> <p>I tried looking into the theme's function.php to copy the codes to my new child theme, but in the code it is refering to a lot of variables which I don't understand.</p> <p>Can anyone help me please?</p>
[ { "answer_id": 360146, "author": "KiwisTasteGood", "author_id": 81335, "author_profile": "https://wordpress.stackexchange.com/users/81335", "pm_score": -1, "selected": false, "text": "<p>In your old theme copy all of the code that registers the post \"type register_post_type()\" etc into the functions.php of the new theme.</p>\n" }, { "answer_id": 360147, "author": "Dominique Pijnenburg", "author_id": 154594, "author_profile": "https://wordpress.stackexchange.com/users/154594", "pm_score": 0, "selected": false, "text": "<p>You can create a new folder in the plugins folder, called something like 'custom-taxonomy'. Create a file with the name 'custom-taxonomy.php' and paste the code below in it. The words 'Image' and 'Images' should be replaced with the name of the custom taxonomy of your current theme.</p>\n\n<p>Don't forget to activate the plugin. Also, it could be that you'll need to change the true/false values for things like 'public' and 'has_archive'.</p>\n\n<pre><code>/**\n * Plugin Name: Custom Post Type\n * Plugin URI: http://www.mywebsite.com/my-first-plugin\n * Description: The very first plugin that I have ever created.\n * Version: 1.0\n * Author: Your Name\n * Author URI: http://www.mywebsite.com\n */ \n\nfunction custom_post_type() {\n $post_names = array(\n 'slug' =&gt; 'image',\n 'singular' =&gt; __( 'Image', 'plugin-name' ),\n 'plural' =&gt; __( 'Images', 'plugin-name' )\n );\n\n register_post_type( strtolower($post_names['slug']),\n array(\n 'labels' =&gt; array(\n 'name' =&gt; $post_names['plural'],\n 'singular_name' =&gt; $post_names['singular'],\n 'add_new' =&gt; sprintf( __( 'Add new %s', 'plugin-name' ), strtolower($post_names['singular']) ),\n 'add_new_item' =&gt; sprintf( __( 'Add new %s', 'plugin-name' ), strtolower($post_names['singular']) ),\n 'edit' =&gt; sprintf( __( 'Edit %s', 'plugin-name' ), strtolower($post_names['singular']) ),\n 'edit_item' =&gt; sprintf( __( 'Edit %s', 'plugin-name' ), strtolower($post_names['singular'] )),\n 'new_item' =&gt; sprintf( __( 'New %s', 'plugin-name' ), strtolower($post_names['singular'] )),\n 'all_items' =&gt; sprintf( __( 'All %s', 'plugin-name' ), strtolower($post_names['plural'] )),\n 'view' =&gt; sprintf( __( 'View %s', 'plugin-name' ), strtolower($post_names['singular'] )),\n 'view_item' =&gt; sprintf( __( 'View %s', 'plugin-name' ), strtolower($post_names['singular'] )),\n 'search_items' =&gt; sprintf( __( 'Search %s', 'plugin-name' ), strtolower($post_names['plural'] )),\n 'not_found' =&gt; sprintf( __( 'No %s found', 'plugin-name' ), strtolower($post_names['plural']) ),\n 'not_found_in_trash' =&gt; sprintf( __( 'No %s found in trash', 'plugin-name' ), strtolower($post_names['plural'] )),\n 'parent_item_colon' =&gt; '' /* text for parent types */\n ),\n 'description' =&gt; sprintf(__( 'Create an %s', 'plugin-name' ), strtolower($post_names['singular'])),\n 'public' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'publicly_queryable' =&gt; true,\n /* queries can be performed on the front end */\n 'has_archive' =&gt; true,\n 'rewrite' =&gt; array(),\n 'menu_position' =&gt; 5,\n 'show_in_nav_menus' =&gt; true,\n 'menu_icon' =&gt; 'dashicons-images-alt2',\n 'hierarchical' =&gt; true,\n 'query_var' =&gt; true,\n 'show_in_rest' =&gt; true,\n /* Sets the query_var key for this post type. Default: true - set to $post_type */\n 'supports' =&gt; array( 'title', 'editor', 'thumbnail', 'revisions', 'excerpt', 'page-attributes'),\n )\n );\n }\n add_action( 'init', 'custom_post_types', 11 );\n</code></pre>\n" }, { "answer_id": 360154, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>You can use <code>unregister_post_type('slug')</code> - where 'slug' is the CPT, such as 'portfolio' or 'book' or whatever your particular CPT is, and then re-register the CPT. I would suggest doing this in your own custom plugin so you can change themes freely.</p>\n\n<p>So if your CPT is 'portfolio' you can create a file in <code>/wp-content/plugins/wpse_360145_create_cpt/create-cpt.php</code>:</p>\n\n<pre><code>&lt;?php\n/* Plugin Name: Create CPT */\n\n// Run everything when the plugin is activated\nregister_activation_hook(__FILE__, 'wpse_360145_activation');\nfunction wpse_360145_activation() {\n // First, unregister the post type\n // (be sure to set this to *your* CPT)\n unregister_post_type('portfolio');\n // Next, re-register it from scratch\n // (You may have to play around with the settings)\n register_post_type('portfolio',\n array(\n // Plural, human-readable label for menu\n 'label' =&gt; 'Portfolio Pieces',\n // Show in REST API must be true for the Block Editor\n 'show_in_rest' =&gt; true,\n // Enable Title, Editor, and Excerpt\n 'supports' =&gt; array('title', 'editor', 'excerpt'),\n // has_archive will create http://example.com/portfolio\n // much like a Post Category archive\n 'has_archive' =&gt; 'portfolio'\n )\n );\n}\n?&gt;\n</code></pre>\n\n<p>There are a number of other settings CPTs can have, so you may have to look up each parameter and adjust to make the CPT work exactly the way you want it to. See <a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\">register_post_type() in the Code Reference</a>.</p>\n\n<p>With this approach, you just activate the plugin to try the settings, and if anything needs tweaking, deactivate, make the changes, and reactivate, and the <code>unregister_post_type()</code> call will make sure the old attempt is completely cleared out.</p>\n" } ]
2020/03/06
[ "https://wordpress.stackexchange.com/questions/360145", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183906/" ]
I used a theme, which created a custom type. Now I want to change the theme, but when I disable the theme, the custom type is also disabled. I tried using CPT plugin, and re-create the custom type, but it tells me that the custom type is already present and it can't recreate it. I tried looking into the theme's function.php to copy the codes to my new child theme, but in the code it is refering to a lot of variables which I don't understand. Can anyone help me please?
You can create a new folder in the plugins folder, called something like 'custom-taxonomy'. Create a file with the name 'custom-taxonomy.php' and paste the code below in it. The words 'Image' and 'Images' should be replaced with the name of the custom taxonomy of your current theme. Don't forget to activate the plugin. Also, it could be that you'll need to change the true/false values for things like 'public' and 'has\_archive'. ``` /** * Plugin Name: Custom Post Type * Plugin URI: http://www.mywebsite.com/my-first-plugin * Description: The very first plugin that I have ever created. * Version: 1.0 * Author: Your Name * Author URI: http://www.mywebsite.com */ function custom_post_type() { $post_names = array( 'slug' => 'image', 'singular' => __( 'Image', 'plugin-name' ), 'plural' => __( 'Images', 'plugin-name' ) ); register_post_type( strtolower($post_names['slug']), array( 'labels' => array( 'name' => $post_names['plural'], 'singular_name' => $post_names['singular'], 'add_new' => sprintf( __( 'Add new %s', 'plugin-name' ), strtolower($post_names['singular']) ), 'add_new_item' => sprintf( __( 'Add new %s', 'plugin-name' ), strtolower($post_names['singular']) ), 'edit' => sprintf( __( 'Edit %s', 'plugin-name' ), strtolower($post_names['singular']) ), 'edit_item' => sprintf( __( 'Edit %s', 'plugin-name' ), strtolower($post_names['singular'] )), 'new_item' => sprintf( __( 'New %s', 'plugin-name' ), strtolower($post_names['singular'] )), 'all_items' => sprintf( __( 'All %s', 'plugin-name' ), strtolower($post_names['plural'] )), 'view' => sprintf( __( 'View %s', 'plugin-name' ), strtolower($post_names['singular'] )), 'view_item' => sprintf( __( 'View %s', 'plugin-name' ), strtolower($post_names['singular'] )), 'search_items' => sprintf( __( 'Search %s', 'plugin-name' ), strtolower($post_names['plural'] )), 'not_found' => sprintf( __( 'No %s found', 'plugin-name' ), strtolower($post_names['plural']) ), 'not_found_in_trash' => sprintf( __( 'No %s found in trash', 'plugin-name' ), strtolower($post_names['plural'] )), 'parent_item_colon' => '' /* text for parent types */ ), 'description' => sprintf(__( 'Create an %s', 'plugin-name' ), strtolower($post_names['singular'])), 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'publicly_queryable' => true, /* queries can be performed on the front end */ 'has_archive' => true, 'rewrite' => array(), 'menu_position' => 5, 'show_in_nav_menus' => true, 'menu_icon' => 'dashicons-images-alt2', 'hierarchical' => true, 'query_var' => true, 'show_in_rest' => true, /* Sets the query_var key for this post type. Default: true - set to $post_type */ 'supports' => array( 'title', 'editor', 'thumbnail', 'revisions', 'excerpt', 'page-attributes'), ) ); } add_action( 'init', 'custom_post_types', 11 ); ```
360,187
<p>If I for example filter my custom post type by date and it only shows 2 records on screen, I only want to export those 2 records, but it is exporting a bunch of records out of my control ie: the wrong records. </p> <p>How can I modify this to only export what is showing up on screen ie: the 2 records in this case?</p> <pre><code>add_action( 'init', 'func_export_some_records' ); function func_export_all_posts() { if(isset($_GET['export_some_records'])) { $arg = array( 'post_type' =&gt; 'shirts', 'fields' =&gt; 'ids' ); global $post; $arr_post = get_posts($arg); if ($arr_post) { header("Content-Description: File Transfer"); header("Content-Type: application/csv"); header('Content-Disposition: attachment; filename="wp.csv"'); header('Pragma: no-cache'); header('Expires: 0'); $file = fopen('php://output', 'w'); fputcsv($file, array('COLUMN ONE', 'COLUMN TWO')); foreach ($arr_post as $post) { $color = get_post_meta( $post, 'user-color', true ); $size = get_post_meta( $post, 'user-size', true ); fputcsv($file, array($color, $size)); } fclose($file); } } } </code></pre> <p>Here is the button that triggers the download:</p> <pre><code>add_action( 'manage_posts_extra_tablenav', 'admin_post_list_top_export_button', 20, 1 ); function admin_post_list_top_export_button( $which ) { global $typenow; if ( 'shirts' === $typenow &amp;&amp; 'top' === $which ) { ?&gt; &lt;input type="submit" name="export_some_records" id="export_some_records" class="button button-primary" value="Export Some Records" /&gt; &lt;?php } </code></pre> <p>}</p> <p>One way I thought of but not actually sure how to achieve is to get all the post ID's currently on screen and then in my $arg array use <code>'includes' =&gt; 'post id here'</code></p>
[ { "answer_id": 360146, "author": "KiwisTasteGood", "author_id": 81335, "author_profile": "https://wordpress.stackexchange.com/users/81335", "pm_score": -1, "selected": false, "text": "<p>In your old theme copy all of the code that registers the post \"type register_post_type()\" etc into the functions.php of the new theme.</p>\n" }, { "answer_id": 360147, "author": "Dominique Pijnenburg", "author_id": 154594, "author_profile": "https://wordpress.stackexchange.com/users/154594", "pm_score": 0, "selected": false, "text": "<p>You can create a new folder in the plugins folder, called something like 'custom-taxonomy'. Create a file with the name 'custom-taxonomy.php' and paste the code below in it. The words 'Image' and 'Images' should be replaced with the name of the custom taxonomy of your current theme.</p>\n\n<p>Don't forget to activate the plugin. Also, it could be that you'll need to change the true/false values for things like 'public' and 'has_archive'.</p>\n\n<pre><code>/**\n * Plugin Name: Custom Post Type\n * Plugin URI: http://www.mywebsite.com/my-first-plugin\n * Description: The very first plugin that I have ever created.\n * Version: 1.0\n * Author: Your Name\n * Author URI: http://www.mywebsite.com\n */ \n\nfunction custom_post_type() {\n $post_names = array(\n 'slug' =&gt; 'image',\n 'singular' =&gt; __( 'Image', 'plugin-name' ),\n 'plural' =&gt; __( 'Images', 'plugin-name' )\n );\n\n register_post_type( strtolower($post_names['slug']),\n array(\n 'labels' =&gt; array(\n 'name' =&gt; $post_names['plural'],\n 'singular_name' =&gt; $post_names['singular'],\n 'add_new' =&gt; sprintf( __( 'Add new %s', 'plugin-name' ), strtolower($post_names['singular']) ),\n 'add_new_item' =&gt; sprintf( __( 'Add new %s', 'plugin-name' ), strtolower($post_names['singular']) ),\n 'edit' =&gt; sprintf( __( 'Edit %s', 'plugin-name' ), strtolower($post_names['singular']) ),\n 'edit_item' =&gt; sprintf( __( 'Edit %s', 'plugin-name' ), strtolower($post_names['singular'] )),\n 'new_item' =&gt; sprintf( __( 'New %s', 'plugin-name' ), strtolower($post_names['singular'] )),\n 'all_items' =&gt; sprintf( __( 'All %s', 'plugin-name' ), strtolower($post_names['plural'] )),\n 'view' =&gt; sprintf( __( 'View %s', 'plugin-name' ), strtolower($post_names['singular'] )),\n 'view_item' =&gt; sprintf( __( 'View %s', 'plugin-name' ), strtolower($post_names['singular'] )),\n 'search_items' =&gt; sprintf( __( 'Search %s', 'plugin-name' ), strtolower($post_names['plural'] )),\n 'not_found' =&gt; sprintf( __( 'No %s found', 'plugin-name' ), strtolower($post_names['plural']) ),\n 'not_found_in_trash' =&gt; sprintf( __( 'No %s found in trash', 'plugin-name' ), strtolower($post_names['plural'] )),\n 'parent_item_colon' =&gt; '' /* text for parent types */\n ),\n 'description' =&gt; sprintf(__( 'Create an %s', 'plugin-name' ), strtolower($post_names['singular'])),\n 'public' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'publicly_queryable' =&gt; true,\n /* queries can be performed on the front end */\n 'has_archive' =&gt; true,\n 'rewrite' =&gt; array(),\n 'menu_position' =&gt; 5,\n 'show_in_nav_menus' =&gt; true,\n 'menu_icon' =&gt; 'dashicons-images-alt2',\n 'hierarchical' =&gt; true,\n 'query_var' =&gt; true,\n 'show_in_rest' =&gt; true,\n /* Sets the query_var key for this post type. Default: true - set to $post_type */\n 'supports' =&gt; array( 'title', 'editor', 'thumbnail', 'revisions', 'excerpt', 'page-attributes'),\n )\n );\n }\n add_action( 'init', 'custom_post_types', 11 );\n</code></pre>\n" }, { "answer_id": 360154, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>You can use <code>unregister_post_type('slug')</code> - where 'slug' is the CPT, such as 'portfolio' or 'book' or whatever your particular CPT is, and then re-register the CPT. I would suggest doing this in your own custom plugin so you can change themes freely.</p>\n\n<p>So if your CPT is 'portfolio' you can create a file in <code>/wp-content/plugins/wpse_360145_create_cpt/create-cpt.php</code>:</p>\n\n<pre><code>&lt;?php\n/* Plugin Name: Create CPT */\n\n// Run everything when the plugin is activated\nregister_activation_hook(__FILE__, 'wpse_360145_activation');\nfunction wpse_360145_activation() {\n // First, unregister the post type\n // (be sure to set this to *your* CPT)\n unregister_post_type('portfolio');\n // Next, re-register it from scratch\n // (You may have to play around with the settings)\n register_post_type('portfolio',\n array(\n // Plural, human-readable label for menu\n 'label' =&gt; 'Portfolio Pieces',\n // Show in REST API must be true for the Block Editor\n 'show_in_rest' =&gt; true,\n // Enable Title, Editor, and Excerpt\n 'supports' =&gt; array('title', 'editor', 'excerpt'),\n // has_archive will create http://example.com/portfolio\n // much like a Post Category archive\n 'has_archive' =&gt; 'portfolio'\n )\n );\n}\n?&gt;\n</code></pre>\n\n<p>There are a number of other settings CPTs can have, so you may have to look up each parameter and adjust to make the CPT work exactly the way you want it to. See <a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\">register_post_type() in the Code Reference</a>.</p>\n\n<p>With this approach, you just activate the plugin to try the settings, and if anything needs tweaking, deactivate, make the changes, and reactivate, and the <code>unregister_post_type()</code> call will make sure the old attempt is completely cleared out.</p>\n" } ]
2020/03/07
[ "https://wordpress.stackexchange.com/questions/360187", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/165412/" ]
If I for example filter my custom post type by date and it only shows 2 records on screen, I only want to export those 2 records, but it is exporting a bunch of records out of my control ie: the wrong records. How can I modify this to only export what is showing up on screen ie: the 2 records in this case? ``` add_action( 'init', 'func_export_some_records' ); function func_export_all_posts() { if(isset($_GET['export_some_records'])) { $arg = array( 'post_type' => 'shirts', 'fields' => 'ids' ); global $post; $arr_post = get_posts($arg); if ($arr_post) { header("Content-Description: File Transfer"); header("Content-Type: application/csv"); header('Content-Disposition: attachment; filename="wp.csv"'); header('Pragma: no-cache'); header('Expires: 0'); $file = fopen('php://output', 'w'); fputcsv($file, array('COLUMN ONE', 'COLUMN TWO')); foreach ($arr_post as $post) { $color = get_post_meta( $post, 'user-color', true ); $size = get_post_meta( $post, 'user-size', true ); fputcsv($file, array($color, $size)); } fclose($file); } } } ``` Here is the button that triggers the download: ``` add_action( 'manage_posts_extra_tablenav', 'admin_post_list_top_export_button', 20, 1 ); function admin_post_list_top_export_button( $which ) { global $typenow; if ( 'shirts' === $typenow && 'top' === $which ) { ?> <input type="submit" name="export_some_records" id="export_some_records" class="button button-primary" value="Export Some Records" /> <?php } ``` } One way I thought of but not actually sure how to achieve is to get all the post ID's currently on screen and then in my $arg array use `'includes' => 'post id here'`
You can create a new folder in the plugins folder, called something like 'custom-taxonomy'. Create a file with the name 'custom-taxonomy.php' and paste the code below in it. The words 'Image' and 'Images' should be replaced with the name of the custom taxonomy of your current theme. Don't forget to activate the plugin. Also, it could be that you'll need to change the true/false values for things like 'public' and 'has\_archive'. ``` /** * Plugin Name: Custom Post Type * Plugin URI: http://www.mywebsite.com/my-first-plugin * Description: The very first plugin that I have ever created. * Version: 1.0 * Author: Your Name * Author URI: http://www.mywebsite.com */ function custom_post_type() { $post_names = array( 'slug' => 'image', 'singular' => __( 'Image', 'plugin-name' ), 'plural' => __( 'Images', 'plugin-name' ) ); register_post_type( strtolower($post_names['slug']), array( 'labels' => array( 'name' => $post_names['plural'], 'singular_name' => $post_names['singular'], 'add_new' => sprintf( __( 'Add new %s', 'plugin-name' ), strtolower($post_names['singular']) ), 'add_new_item' => sprintf( __( 'Add new %s', 'plugin-name' ), strtolower($post_names['singular']) ), 'edit' => sprintf( __( 'Edit %s', 'plugin-name' ), strtolower($post_names['singular']) ), 'edit_item' => sprintf( __( 'Edit %s', 'plugin-name' ), strtolower($post_names['singular'] )), 'new_item' => sprintf( __( 'New %s', 'plugin-name' ), strtolower($post_names['singular'] )), 'all_items' => sprintf( __( 'All %s', 'plugin-name' ), strtolower($post_names['plural'] )), 'view' => sprintf( __( 'View %s', 'plugin-name' ), strtolower($post_names['singular'] )), 'view_item' => sprintf( __( 'View %s', 'plugin-name' ), strtolower($post_names['singular'] )), 'search_items' => sprintf( __( 'Search %s', 'plugin-name' ), strtolower($post_names['plural'] )), 'not_found' => sprintf( __( 'No %s found', 'plugin-name' ), strtolower($post_names['plural']) ), 'not_found_in_trash' => sprintf( __( 'No %s found in trash', 'plugin-name' ), strtolower($post_names['plural'] )), 'parent_item_colon' => '' /* text for parent types */ ), 'description' => sprintf(__( 'Create an %s', 'plugin-name' ), strtolower($post_names['singular'])), 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'publicly_queryable' => true, /* queries can be performed on the front end */ 'has_archive' => true, 'rewrite' => array(), 'menu_position' => 5, 'show_in_nav_menus' => true, 'menu_icon' => 'dashicons-images-alt2', 'hierarchical' => true, 'query_var' => true, 'show_in_rest' => true, /* Sets the query_var key for this post type. Default: true - set to $post_type */ 'supports' => array( 'title', 'editor', 'thumbnail', 'revisions', 'excerpt', 'page-attributes'), ) ); } add_action( 'init', 'custom_post_types', 11 ); ```
360,207
<p>I have registered settings and need it to be showed in REST API. </p> <pre><code>$args = [ 'show_in_rest' =&gt; true ]; register_setting('default_sidebars', 'default_sidebars', $args); </code></pre> <p>When I save a single value and then request data on endpoint <code>/wp-json/wp/v2/settings</code>, everything works perfectly.</p> <p>But the problem is that I save serialized data like this.</p> <pre><code>a:2:{s:4:"post";s:7:"general";s:4:"blog";s:9:"sidebar_1";} </code></pre> <p>Now I would expect in response something like this:</p> <pre><code>default_sidebars: { post: "general", blog: "sidebar_1" } </code></pre> <p>But instead I got <code>default_sidebars: null</code>.</p> <p>What should I do to get my data in REST API?</p>
[ { "answer_id": 360218, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": false, "text": "<p><em>Not sure if there's a <strong>better</strong> way when using the default Settings endpoint, but this works for me.</em></p>\n\n<p>You can use the <a href=\"https://developer.wordpress.org/reference/hooks/rest_pre_get_setting/\" rel=\"nofollow noreferrer\"><code>rest_pre_get_setting</code> hook</a> to convert the data to a JSON-encoded string:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'rest_pre_get_setting', function ( $value, $name ) {\n if ( 'default_sidebars' === $name ) {\n $value = json_encode( get_option( $name ) );\n }\n return $value;\n}, 10, 2 );\n</code></pre>\n\n<p>Then for example in JavaScript, you can parse the value into an object using <code>JSON.parse()</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Note: I intentionally omitted the authentication/nonce part.\nfetch( 'https://example.com/wp-json/wp/v2/settings' )\n .then( res =&gt; res.json() )\n .then( settings =&gt; console.log( JSON.parse( settings.default_sidebars ) ) );\n</code></pre>\n\n<p>Or in PHP (e.g. you make the API request from another site using PHP), you can do:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$settings = json_decode( $data ); // assume data is the REST API response body\n$default_sidebars = json_decode( $settings-&gt;default_sidebars );\n</code></pre>\n\n<h2>Additional Notes</h2>\n\n<p>The <code>null</code> value is because <code>get_option()</code> unserializes the data to an array and the REST API controller for the Settings endpoint is using <a href=\"https://developer.wordpress.org/reference/functions/rest_validate_value_from_schema/\" rel=\"nofollow noreferrer\"><code>rest_validate_value_from_schema()</code></a> to validate the option value (i.e. after being unserialized), which when it's not of the currently supported types (string, boolean, integer and number) &mdash; see <a href=\"https://developer.wordpress.org/reference/functions/register_setting/\" rel=\"nofollow noreferrer\"><code>register_setting()</code></a>, then the function returns an error and the Settings endpoint/controller returns a <code>null</code> for that specific option.</p>\n\n<h2>Alternate Solution</h2>\n\n<p>You can <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">create a custom REST API endpoint</a> and with the following example, you would make request to <code>/wp-json/myplugin/v1/setting/&lt;option name&gt;</code> where <code>&lt;option name&gt;</code> could be <code>default_sidebars</code> in your case:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'rest_api_init', function () {\n register_rest_route( 'myplugin/v1', '/setting/(?P&lt;name&gt;[a-zA-Z0-9\\-_]+)', [\n 'methods' =&gt; 'GET',\n 'callback' =&gt; function ( $request ) {\n return get_option( $request-&gt;get_param( 'name' ) );\n },\n 'permission_callback' =&gt; function () {\n return current_user_can( 'manage_options' ); // you should keep this\n },\n ] );\n} );\n</code></pre>\n" }, { "answer_id": 360237, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<h2>JSON Schema</h2>\n\n<p>It's supported if you explicitly register the <strong>object JSON schema</strong> as:</p>\n\n<pre><code>$args = array(\n 'show_in_rest' =&gt; array(\n 'schema' =&gt; array(\n 'type' =&gt; 'object',\n 'properties' =&gt; array(\n 'post' =&gt; array(\n 'type' =&gt; 'string',\n ),\n 'blog' =&gt; array(\n 'type' =&gt; 'string',\n ),\n )\n ),\n ),\n);\n\nregister_setting( 'default_sidebars', 'default_sidebars', $args );\n</code></pre>\n\n<p>Resulting in the following object:</p>\n\n<pre><code>default_sidebars: {\n post: \"general\",\n blog: \"sidebar_1\"\n}\n</code></pre>\n\n<p>in <code>/wp-json/wp/v2/settings</code> for the serialized option data: </p>\n\n<pre><code>a:2:{s:4:\"post\";s:7:\"general\";s:4:\"blog\";s:9:\"sidebar_1\";}\n</code></pre>\n\n<p>See similar object schema support for <code>register_meta()</code> in 5.3:</p>\n\n<p><a href=\"https://make.wordpress.org/core/2019/10/03/wp-5-3-supports-object-and-array-meta-types-in-the-rest-api/\" rel=\"noreferrer\">https://make.wordpress.org/core/2019/10/03/wp-5-3-supports-object-and-array-meta-types-in-the-rest-api/</a></p>\n" } ]
2020/03/07
[ "https://wordpress.stackexchange.com/questions/360207", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/157270/" ]
I have registered settings and need it to be showed in REST API. ``` $args = [ 'show_in_rest' => true ]; register_setting('default_sidebars', 'default_sidebars', $args); ``` When I save a single value and then request data on endpoint `/wp-json/wp/v2/settings`, everything works perfectly. But the problem is that I save serialized data like this. ``` a:2:{s:4:"post";s:7:"general";s:4:"blog";s:9:"sidebar_1";} ``` Now I would expect in response something like this: ``` default_sidebars: { post: "general", blog: "sidebar_1" } ``` But instead I got `default_sidebars: null`. What should I do to get my data in REST API?
JSON Schema ----------- It's supported if you explicitly register the **object JSON schema** as: ``` $args = array( 'show_in_rest' => array( 'schema' => array( 'type' => 'object', 'properties' => array( 'post' => array( 'type' => 'string', ), 'blog' => array( 'type' => 'string', ), ) ), ), ); register_setting( 'default_sidebars', 'default_sidebars', $args ); ``` Resulting in the following object: ``` default_sidebars: { post: "general", blog: "sidebar_1" } ``` in `/wp-json/wp/v2/settings` for the serialized option data: ``` a:2:{s:4:"post";s:7:"general";s:4:"blog";s:9:"sidebar_1";} ``` See similar object schema support for `register_meta()` in 5.3: <https://make.wordpress.org/core/2019/10/03/wp-5-3-supports-object-and-array-meta-types-in-the-rest-api/>
360,209
<p>I am struggling with the translations of my theme. I use the function <code>get_permalink_date</code> of my class. The relevant snippet is:</p> <pre><code>$permalink_title = sprintf( /* translators: 1 = Post Title, 2 = Author Name */ esc_html_x( '%1$s by %2$s', 'permalink title', 'themeberger' ), __( 'A post', 'themeberger' ), get_the_author_meta( 'display_name', $this-&gt;post-&gt;post_author ) ); </code></pre> <p>What I don't understand is that the translation from <code>__();</code> works, but <code>esc_html_x();</code> does not. I hope that someone can help me.</p> <p>The relevant part from the .po file is:</p> <pre><code>#. translators: %1$s: Post Title. %2$s: Author Name. #: themeberger/class-themeberger-post-functions.php:237 msgid "%1$s by %2$s" msgstr "%1$s von %2$s" #: themeberger/class-themeberger-post-functions.php:238 msgid "A post" msgstr "Ein Beitrag" </code></pre> <p>The output is <code>&lt;a href="[...]" title="Ein Beitrag by Christian Hockenberger"&gt;[...]&lt;/a&gt;</code></p> <p>I really don't get it. In another line also <code>_x( '%s ago', '%s = human-readable time difference', 'themeberger' )</code> is not working. I first thought that for some reason the translations are not transferred to the class, but <code>__();</code> works.</p> <p><strong>What can I do?</strong></p>
[ { "answer_id": 360218, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": false, "text": "<p><em>Not sure if there's a <strong>better</strong> way when using the default Settings endpoint, but this works for me.</em></p>\n\n<p>You can use the <a href=\"https://developer.wordpress.org/reference/hooks/rest_pre_get_setting/\" rel=\"nofollow noreferrer\"><code>rest_pre_get_setting</code> hook</a> to convert the data to a JSON-encoded string:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'rest_pre_get_setting', function ( $value, $name ) {\n if ( 'default_sidebars' === $name ) {\n $value = json_encode( get_option( $name ) );\n }\n return $value;\n}, 10, 2 );\n</code></pre>\n\n<p>Then for example in JavaScript, you can parse the value into an object using <code>JSON.parse()</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Note: I intentionally omitted the authentication/nonce part.\nfetch( 'https://example.com/wp-json/wp/v2/settings' )\n .then( res =&gt; res.json() )\n .then( settings =&gt; console.log( JSON.parse( settings.default_sidebars ) ) );\n</code></pre>\n\n<p>Or in PHP (e.g. you make the API request from another site using PHP), you can do:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$settings = json_decode( $data ); // assume data is the REST API response body\n$default_sidebars = json_decode( $settings-&gt;default_sidebars );\n</code></pre>\n\n<h2>Additional Notes</h2>\n\n<p>The <code>null</code> value is because <code>get_option()</code> unserializes the data to an array and the REST API controller for the Settings endpoint is using <a href=\"https://developer.wordpress.org/reference/functions/rest_validate_value_from_schema/\" rel=\"nofollow noreferrer\"><code>rest_validate_value_from_schema()</code></a> to validate the option value (i.e. after being unserialized), which when it's not of the currently supported types (string, boolean, integer and number) &mdash; see <a href=\"https://developer.wordpress.org/reference/functions/register_setting/\" rel=\"nofollow noreferrer\"><code>register_setting()</code></a>, then the function returns an error and the Settings endpoint/controller returns a <code>null</code> for that specific option.</p>\n\n<h2>Alternate Solution</h2>\n\n<p>You can <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">create a custom REST API endpoint</a> and with the following example, you would make request to <code>/wp-json/myplugin/v1/setting/&lt;option name&gt;</code> where <code>&lt;option name&gt;</code> could be <code>default_sidebars</code> in your case:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'rest_api_init', function () {\n register_rest_route( 'myplugin/v1', '/setting/(?P&lt;name&gt;[a-zA-Z0-9\\-_]+)', [\n 'methods' =&gt; 'GET',\n 'callback' =&gt; function ( $request ) {\n return get_option( $request-&gt;get_param( 'name' ) );\n },\n 'permission_callback' =&gt; function () {\n return current_user_can( 'manage_options' ); // you should keep this\n },\n ] );\n} );\n</code></pre>\n" }, { "answer_id": 360237, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<h2>JSON Schema</h2>\n\n<p>It's supported if you explicitly register the <strong>object JSON schema</strong> as:</p>\n\n<pre><code>$args = array(\n 'show_in_rest' =&gt; array(\n 'schema' =&gt; array(\n 'type' =&gt; 'object',\n 'properties' =&gt; array(\n 'post' =&gt; array(\n 'type' =&gt; 'string',\n ),\n 'blog' =&gt; array(\n 'type' =&gt; 'string',\n ),\n )\n ),\n ),\n);\n\nregister_setting( 'default_sidebars', 'default_sidebars', $args );\n</code></pre>\n\n<p>Resulting in the following object:</p>\n\n<pre><code>default_sidebars: {\n post: \"general\",\n blog: \"sidebar_1\"\n}\n</code></pre>\n\n<p>in <code>/wp-json/wp/v2/settings</code> for the serialized option data: </p>\n\n<pre><code>a:2:{s:4:\"post\";s:7:\"general\";s:4:\"blog\";s:9:\"sidebar_1\";}\n</code></pre>\n\n<p>See similar object schema support for <code>register_meta()</code> in 5.3:</p>\n\n<p><a href=\"https://make.wordpress.org/core/2019/10/03/wp-5-3-supports-object-and-array-meta-types-in-the-rest-api/\" rel=\"noreferrer\">https://make.wordpress.org/core/2019/10/03/wp-5-3-supports-object-and-array-meta-types-in-the-rest-api/</a></p>\n" } ]
2020/03/07
[ "https://wordpress.stackexchange.com/questions/360209", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/45070/" ]
I am struggling with the translations of my theme. I use the function `get_permalink_date` of my class. The relevant snippet is: ``` $permalink_title = sprintf( /* translators: 1 = Post Title, 2 = Author Name */ esc_html_x( '%1$s by %2$s', 'permalink title', 'themeberger' ), __( 'A post', 'themeberger' ), get_the_author_meta( 'display_name', $this->post->post_author ) ); ``` What I don't understand is that the translation from `__();` works, but `esc_html_x();` does not. I hope that someone can help me. The relevant part from the .po file is: ``` #. translators: %1$s: Post Title. %2$s: Author Name. #: themeberger/class-themeberger-post-functions.php:237 msgid "%1$s by %2$s" msgstr "%1$s von %2$s" #: themeberger/class-themeberger-post-functions.php:238 msgid "A post" msgstr "Ein Beitrag" ``` The output is `<a href="[...]" title="Ein Beitrag by Christian Hockenberger">[...]</a>` I really don't get it. In another line also `_x( '%s ago', '%s = human-readable time difference', 'themeberger' )` is not working. I first thought that for some reason the translations are not transferred to the class, but `__();` works. **What can I do?**
JSON Schema ----------- It's supported if you explicitly register the **object JSON schema** as: ``` $args = array( 'show_in_rest' => array( 'schema' => array( 'type' => 'object', 'properties' => array( 'post' => array( 'type' => 'string', ), 'blog' => array( 'type' => 'string', ), ) ), ), ); register_setting( 'default_sidebars', 'default_sidebars', $args ); ``` Resulting in the following object: ``` default_sidebars: { post: "general", blog: "sidebar_1" } ``` in `/wp-json/wp/v2/settings` for the serialized option data: ``` a:2:{s:4:"post";s:7:"general";s:4:"blog";s:9:"sidebar_1";} ``` See similar object schema support for `register_meta()` in 5.3: <https://make.wordpress.org/core/2019/10/03/wp-5-3-supports-object-and-array-meta-types-in-the-rest-api/>
360,244
<p>I have been looking into setting up WordPress and its plugins and themes using composer. I notice alot of the tutorials around have composer installing wordpress into its own sub directory for example /wp and the themes, plugins, must use plugins to a completely different directory like /content. Is there a reason why it doesn't use /wp/content for the plugins/themes/ect and make /wp the web root? I noticed composer seems to properly install everything this way, so it there something I am missing?</p> <p>EDIT: I should clarify that I am aware that updating core will remove the content directory, however all the plugins/themes are also installed by composer and I don not rely on it for persistent upload storage, I offload my media uploads to S3. So with that in mind is there any other downside to using this setup? Because I really do prefer the more traditional file structure.</p>
[ { "answer_id": 360218, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": false, "text": "<p><em>Not sure if there's a <strong>better</strong> way when using the default Settings endpoint, but this works for me.</em></p>\n\n<p>You can use the <a href=\"https://developer.wordpress.org/reference/hooks/rest_pre_get_setting/\" rel=\"nofollow noreferrer\"><code>rest_pre_get_setting</code> hook</a> to convert the data to a JSON-encoded string:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'rest_pre_get_setting', function ( $value, $name ) {\n if ( 'default_sidebars' === $name ) {\n $value = json_encode( get_option( $name ) );\n }\n return $value;\n}, 10, 2 );\n</code></pre>\n\n<p>Then for example in JavaScript, you can parse the value into an object using <code>JSON.parse()</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Note: I intentionally omitted the authentication/nonce part.\nfetch( 'https://example.com/wp-json/wp/v2/settings' )\n .then( res =&gt; res.json() )\n .then( settings =&gt; console.log( JSON.parse( settings.default_sidebars ) ) );\n</code></pre>\n\n<p>Or in PHP (e.g. you make the API request from another site using PHP), you can do:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$settings = json_decode( $data ); // assume data is the REST API response body\n$default_sidebars = json_decode( $settings-&gt;default_sidebars );\n</code></pre>\n\n<h2>Additional Notes</h2>\n\n<p>The <code>null</code> value is because <code>get_option()</code> unserializes the data to an array and the REST API controller for the Settings endpoint is using <a href=\"https://developer.wordpress.org/reference/functions/rest_validate_value_from_schema/\" rel=\"nofollow noreferrer\"><code>rest_validate_value_from_schema()</code></a> to validate the option value (i.e. after being unserialized), which when it's not of the currently supported types (string, boolean, integer and number) &mdash; see <a href=\"https://developer.wordpress.org/reference/functions/register_setting/\" rel=\"nofollow noreferrer\"><code>register_setting()</code></a>, then the function returns an error and the Settings endpoint/controller returns a <code>null</code> for that specific option.</p>\n\n<h2>Alternate Solution</h2>\n\n<p>You can <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">create a custom REST API endpoint</a> and with the following example, you would make request to <code>/wp-json/myplugin/v1/setting/&lt;option name&gt;</code> where <code>&lt;option name&gt;</code> could be <code>default_sidebars</code> in your case:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'rest_api_init', function () {\n register_rest_route( 'myplugin/v1', '/setting/(?P&lt;name&gt;[a-zA-Z0-9\\-_]+)', [\n 'methods' =&gt; 'GET',\n 'callback' =&gt; function ( $request ) {\n return get_option( $request-&gt;get_param( 'name' ) );\n },\n 'permission_callback' =&gt; function () {\n return current_user_can( 'manage_options' ); // you should keep this\n },\n ] );\n} );\n</code></pre>\n" }, { "answer_id": 360237, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<h2>JSON Schema</h2>\n\n<p>It's supported if you explicitly register the <strong>object JSON schema</strong> as:</p>\n\n<pre><code>$args = array(\n 'show_in_rest' =&gt; array(\n 'schema' =&gt; array(\n 'type' =&gt; 'object',\n 'properties' =&gt; array(\n 'post' =&gt; array(\n 'type' =&gt; 'string',\n ),\n 'blog' =&gt; array(\n 'type' =&gt; 'string',\n ),\n )\n ),\n ),\n);\n\nregister_setting( 'default_sidebars', 'default_sidebars', $args );\n</code></pre>\n\n<p>Resulting in the following object:</p>\n\n<pre><code>default_sidebars: {\n post: \"general\",\n blog: \"sidebar_1\"\n}\n</code></pre>\n\n<p>in <code>/wp-json/wp/v2/settings</code> for the serialized option data: </p>\n\n<pre><code>a:2:{s:4:\"post\";s:7:\"general\";s:4:\"blog\";s:9:\"sidebar_1\";}\n</code></pre>\n\n<p>See similar object schema support for <code>register_meta()</code> in 5.3:</p>\n\n<p><a href=\"https://make.wordpress.org/core/2019/10/03/wp-5-3-supports-object-and-array-meta-types-in-the-rest-api/\" rel=\"noreferrer\">https://make.wordpress.org/core/2019/10/03/wp-5-3-supports-object-and-array-meta-types-in-the-rest-api/</a></p>\n" } ]
2020/03/08
[ "https://wordpress.stackexchange.com/questions/360244", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183961/" ]
I have been looking into setting up WordPress and its plugins and themes using composer. I notice alot of the tutorials around have composer installing wordpress into its own sub directory for example /wp and the themes, plugins, must use plugins to a completely different directory like /content. Is there a reason why it doesn't use /wp/content for the plugins/themes/ect and make /wp the web root? I noticed composer seems to properly install everything this way, so it there something I am missing? EDIT: I should clarify that I am aware that updating core will remove the content directory, however all the plugins/themes are also installed by composer and I don not rely on it for persistent upload storage, I offload my media uploads to S3. So with that in mind is there any other downside to using this setup? Because I really do prefer the more traditional file structure.
JSON Schema ----------- It's supported if you explicitly register the **object JSON schema** as: ``` $args = array( 'show_in_rest' => array( 'schema' => array( 'type' => 'object', 'properties' => array( 'post' => array( 'type' => 'string', ), 'blog' => array( 'type' => 'string', ), ) ), ), ); register_setting( 'default_sidebars', 'default_sidebars', $args ); ``` Resulting in the following object: ``` default_sidebars: { post: "general", blog: "sidebar_1" } ``` in `/wp-json/wp/v2/settings` for the serialized option data: ``` a:2:{s:4:"post";s:7:"general";s:4:"blog";s:9:"sidebar_1";} ``` See similar object schema support for `register_meta()` in 5.3: <https://make.wordpress.org/core/2019/10/03/wp-5-3-supports-object-and-array-meta-types-in-the-rest-api/>
360,254
<p>Is there any difference in using</p> <pre><code>&lt;?php get_the_title(); ?&gt; </code></pre> <p>or</p> <pre><code>&lt;?php single_post_title(); ?&gt; </code></pre> <p>Because I can always get same value </p>
[ { "answer_id": 360271, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 1, "selected": false, "text": "<p>Yes, there are some differences in the two. Lets take a look.</p>\n<p><strong><a href=\"https://developer.wordpress.org/reference/functions/single_post_title/\" rel=\"nofollow noreferrer\">single_post_title()</a></strong></p>\n<blockquote>\n<p>This is optimized for single.php template file for displaying the post title.</p>\n<p>It does not support placing the separator after the title, but by leaving the prefix parameter empty, you can set the title separator manually. The prefix does not automatically place a space between the prefix, so if there should be a space, the parameter value will need to have it at the end.</p>\n</blockquote>\n<p><strong>Parameters</strong></p>\n<p><code>$prefix</code></p>\n<p>(string) (Optional) What to display before the title.</p>\n<p>Default value: ''</p>\n<p><code>$display</code></p>\n<p>(bool) (Optional) Whether to display or retrieve title.</p>\n<p>Default value: true</p>\n<hr />\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_the_title/\" rel=\"nofollow noreferrer\"><strong>get_the_title()</strong></a></p>\n<blockquote>\n<p>If the post is protected and the visitor is not an admin, then &quot;Protected&quot; will be displayed before the post title. If the post is private, then &quot;Private&quot; will be located before the post title.</p>\n</blockquote>\n<p><strong>Parameters</strong></p>\n<p><code>$post</code></p>\n<p>(int|WP_Post) (Optional) Post ID or WP_Post object.</p>\n<p>Default is global $post.</p>\n<hr />\n<p>To be honest I didn't even know there was a single_post_title(). I just use get_the_title() or the_title() depending on if I want the value echoed or not. These can be used anywhere, either by using the global post or passing an ID.</p>\n" }, { "answer_id": 360285, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p><code>single_post_title()</code> and <code>get_the_title()</code> work completely differently.</p>\n\n<p><code>get_the_title()</code> (or <code>the_title()</code>, which works the same) will get the title for the current post in <a href=\"https://developer.wordpress.org/themes/basics/the-loop/\" rel=\"nofollow noreferrer\">the loop</a>:</p>\n\n<pre><code>&lt;?php \nif ( have_posts() ) : \n while ( have_posts() ) : the_post(); \n the_title();\n endwhile; \nendif; \n?&gt;\n</code></pre>\n\n<p>So it's the function to use to get the post title for each post in the template for the blog and archives, when used inside the loop. <code>get_the_title()</code> can also be used to get the title for a specific post. This can be done by passing the ID to the post whose title you want:</p>\n\n<pre><code>echo get_the_title( 123 );\n</code></pre>\n\n<hr>\n\n<p><code>single_post_title()</code>, on the other hand, gets the title of <em>the queried object</em>. When you are on a single post or page, the \"queried object\" will be a <a href=\"https://developer.wordpress.org/reference/classes/wp_post/\" rel=\"nofollow noreferrer\"><code>WP_Post</code></a> representing that post or page, and <code>single_post_title()</code> gets the title of that post. I found <a href=\"https://wpshout.com/get_queried_object-how-and-why-to-use-it-with-examples/\" rel=\"nofollow noreferrer\">this article</a> which describes what the queried object is in more detail.</p>\n\n<p>So on a single template this will almost certainly be the same as the current post in the loop. However, because this function always returns the title of the queried object, you can use it to get the title of the current page outside of the loop, or inside a secondary loop.</p>\n\n<p>Also note, that because the queried object of the blog and archives isn't a single post or page, <code>single_post_title()</code> will not work on those pages. For those pages you want to use <code>the_archive_title()</code>, or for taxonomy archives, <code>single_term_title()</code>.</p>\n" }, { "answer_id": 363330, "author": "John Bauer", "author_id": 176202, "author_profile": "https://wordpress.stackexchange.com/users/176202", "pm_score": 0, "selected": false, "text": "<p>Both are different.</p>\n\n<ol>\n<li>get_the_title( int|WP_Post $post ) - Retrieve post title. </li>\n</ol>\n\n<p>If the post is protected and the visitor is not an admin, then \"Protected\" will be displayed before the post title. If the post is private, then \"Private\" will be located before the post title.</p>\n\n<ol start=\"2\">\n<li>single_post_title( string $prefix = '', bool $display = true ) - Display or retrieve page title for post.</li>\n</ol>\n\n<p>This is optimized for single.php template file for displaying the post title.</p>\n\n<p>It does not support placing the separator after the title, but by leaving the prefix parameter empty, you can set the title separator manually. The prefix does not automatically place a space between the prefix, so if there should be a space, the parameter value will need to have it at the end.</p>\n" } ]
2020/03/08
[ "https://wordpress.stackexchange.com/questions/360254", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175502/" ]
Is there any difference in using ``` <?php get_the_title(); ?> ``` or ``` <?php single_post_title(); ?> ``` Because I can always get same value
`single_post_title()` and `get_the_title()` work completely differently. `get_the_title()` (or `the_title()`, which works the same) will get the title for the current post in [the loop](https://developer.wordpress.org/themes/basics/the-loop/): ``` <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); the_title(); endwhile; endif; ?> ``` So it's the function to use to get the post title for each post in the template for the blog and archives, when used inside the loop. `get_the_title()` can also be used to get the title for a specific post. This can be done by passing the ID to the post whose title you want: ``` echo get_the_title( 123 ); ``` --- `single_post_title()`, on the other hand, gets the title of *the queried object*. When you are on a single post or page, the "queried object" will be a [`WP_Post`](https://developer.wordpress.org/reference/classes/wp_post/) representing that post or page, and `single_post_title()` gets the title of that post. I found [this article](https://wpshout.com/get_queried_object-how-and-why-to-use-it-with-examples/) which describes what the queried object is in more detail. So on a single template this will almost certainly be the same as the current post in the loop. However, because this function always returns the title of the queried object, you can use it to get the title of the current page outside of the loop, or inside a secondary loop. Also note, that because the queried object of the blog and archives isn't a single post or page, `single_post_title()` will not work on those pages. For those pages you want to use `the_archive_title()`, or for taxonomy archives, `single_term_title()`.
360,263
<p>My previous plugin was saving the comments as type="wp_review_comment". I have handled the previous custom fields as below. But I'm having difficulty saving the comments as a custom comment type.</p> <pre><code>// Add default fields add_filter('comment_form_default_fields','custom_fields'); function custom_fields($fields) { $commenter = wp_get_current_commenter(); $req = get_option( 'require_name_email' ); $aria_req = ( $req ? " aria-required='true'" : '' ); $fields[ 'author' ] = '&lt;p class="comment-form-author"&gt;'. '&lt;label for="author"&gt;' . __( 'Name' ) . '&lt;/label&gt;'. ( $req ? '&lt;span class="required"&gt;*&lt;/span&gt;' : '' ). '&lt;input id="author" name="author" type="text" value="'. esc_attr( $commenter['comment_author'] ) . '" size="30" tabindex="1"' . $aria_req . ' /&gt;&lt;/p&gt;'; $fields[ 'email' ] = '&lt;p class="comment-form-email"&gt;'. '&lt;label for="email"&gt;' . __( 'Email' ) . '&lt;/label&gt;'. ( $req ? '&lt;span class="required"&gt;*&lt;/span&gt;' : '' ). '&lt;input id="email" name="email" type="text" value="'. esc_attr( $commenter['comment_author_email'] ) . '" size="30" tabindex="2"' . $aria_req . ' /&gt;&lt;/p&gt;'; $fields[ 'url' ] = '&lt;p class="comment-form-url"&gt;'. '&lt;label for="url"&gt;' . __( 'Website' ) . '&lt;/label&gt;'. '&lt;input id="url" name="url" type="text" value="'. esc_attr( $commenter['comment_author_url'] ) . '" size="30" tabindex="3" /&gt;&lt;/p&gt;'; return $fields; } // Add fields. add_action( 'comment_form_logged_in_after', 'additional_fields' ); add_action( 'comment_form_after_fields', 'additional_fields' ); function additional_fields () { echo '&lt;p class="comment-form-title"&gt;'. '&lt;label for="wp_review_comment_title"&gt;' . __( 'Titley' ) . '&lt;/label&gt;'. '&lt;input id="wp_review_comment_title" name="wp_review_comment_title" type="text" size="30" tabindex="5" /&gt;&lt;/p&gt;'; echo '&lt;p class="comment-form-rating"&gt;'. '&lt;label for="wp_review_comment_rating"&gt;'. __('Ratingy: ') . '&lt;span class="required"&gt;*&lt;/span&gt;&lt;/label&gt; &lt;span class="commentratingbox"&gt;'; for( $i=1; $i &lt;= 5; $i++ ) echo '&lt;span class="commentrating"&gt;&lt;input type="radio" name="wp_review_comment_rating" id="rating" value="'. $i .'"/&gt;'. $i .'&lt;/span&gt;'; echo'&lt;/span&gt;&lt;/p&gt;'; } // Save the comment metadata along with the comment. add_action( 'comment_post', 'save_comment_meta_data' ); function save_comment_meta_data( $comment_id ) { if ( ( isset( $_POST['wp_review_comment_title'] ) ) &amp;&amp; ( $_POST['wp_review_comment_title'] != '') ) $title = wp_filter_nohtml_kses($_POST['wp_review_comment_title']); add_comment_meta( $comment_id, 'wp_review_comment_title', $title ); if ( ( isset( $_POST['wp_review_comment_rating'] ) ) &amp;&amp; ( $_POST['wp_review_comment_rating'] != '') ) $rating = wp_filter_nohtml_kses($_POST['wp_review_comment_rating']); add_comment_meta( $comment_id, 'wp_review_comment_rating', $rating ); } // Check if the comment metadata has been filled or not add_filter( 'preprocess_comment', 'verify_comment_meta_data' ); function verify_comment_meta_data( $commentdata ) { if ( ! isset( $_POST['wp_review_comment_rating'] ) ) wp_die( __( 'A rating is requird. Hit the BACK button and resubmit your review with a rating.' ) ); return $commentdata; } </code></pre> <p>Now, my comments are saved as default comment-type="comment". How do I save the comment as a custom comment type "wp_review_comment"?</p>
[ { "answer_id": 360517, "author": "Asha", "author_id": 92824, "author_profile": "https://wordpress.stackexchange.com/users/92824", "pm_score": 2, "selected": false, "text": "<pre><code> $data = array(\n 'comment_post_ID' =&gt; $post_id,\n 'comment_author' =&gt; 'admin',\n 'comment_content' =&gt; $comment,\n 'user_id' =&gt; $current_user-&gt;ID,\n 'comment_date' =&gt; $time,\n 'comment_approved' =&gt; 1,\n 'comment_type' =&gt; 'custom-comment-class'\n);\nwp_insert_comment($data);\n</code></pre>\n" }, { "answer_id": 360531, "author": "Mikhail", "author_id": 88888, "author_profile": "https://wordpress.stackexchange.com/users/88888", "pm_score": 2, "selected": true, "text": "<p>In addition. You already have code which can kind of do what you need.</p>\n\n<pre><code>add_filter( 'preprocess_comment', 'verify_comment_meta_data' );\nfunction verify_comment_meta_data( $commentdata ) {\n if ( ! isset( $_POST['wp_review_comment_rating'] ) )\n wp_die( __( 'A rating is required. Hit the BACK button and resubmit your review with a rating.' ) );\n // this is filter and $commentdata has comment_type parameter in it. so you need to do this\n $commentdata['comment_type'] = 'wp_review_comment';\n\n return $commentdata;\n}\n</code></pre>\n\n<p>This will do what you wanted but now all your newly created comments will become this type of <code>wp_review_comment</code>, so if you need them the other way - you'll need some kind of conditionals in this filter instead of forcing all comments to have <code>wp_review_comment_rating</code> and forcing them to be <code>wp_review_comment</code> type or die(), preventing from saving.</p>\n\n<p>See <a href=\"https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/comment.php#L1874\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/comment.php#L1874</a> for more details </p>\n" } ]
2020/03/08
[ "https://wordpress.stackexchange.com/questions/360263", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145504/" ]
My previous plugin was saving the comments as type="wp\_review\_comment". I have handled the previous custom fields as below. But I'm having difficulty saving the comments as a custom comment type. ``` // Add default fields add_filter('comment_form_default_fields','custom_fields'); function custom_fields($fields) { $commenter = wp_get_current_commenter(); $req = get_option( 'require_name_email' ); $aria_req = ( $req ? " aria-required='true'" : '' ); $fields[ 'author' ] = '<p class="comment-form-author">'. '<label for="author">' . __( 'Name' ) . '</label>'. ( $req ? '<span class="required">*</span>' : '' ). '<input id="author" name="author" type="text" value="'. esc_attr( $commenter['comment_author'] ) . '" size="30" tabindex="1"' . $aria_req . ' /></p>'; $fields[ 'email' ] = '<p class="comment-form-email">'. '<label for="email">' . __( 'Email' ) . '</label>'. ( $req ? '<span class="required">*</span>' : '' ). '<input id="email" name="email" type="text" value="'. esc_attr( $commenter['comment_author_email'] ) . '" size="30" tabindex="2"' . $aria_req . ' /></p>'; $fields[ 'url' ] = '<p class="comment-form-url">'. '<label for="url">' . __( 'Website' ) . '</label>'. '<input id="url" name="url" type="text" value="'. esc_attr( $commenter['comment_author_url'] ) . '" size="30" tabindex="3" /></p>'; return $fields; } // Add fields. add_action( 'comment_form_logged_in_after', 'additional_fields' ); add_action( 'comment_form_after_fields', 'additional_fields' ); function additional_fields () { echo '<p class="comment-form-title">'. '<label for="wp_review_comment_title">' . __( 'Titley' ) . '</label>'. '<input id="wp_review_comment_title" name="wp_review_comment_title" type="text" size="30" tabindex="5" /></p>'; echo '<p class="comment-form-rating">'. '<label for="wp_review_comment_rating">'. __('Ratingy: ') . '<span class="required">*</span></label> <span class="commentratingbox">'; for( $i=1; $i <= 5; $i++ ) echo '<span class="commentrating"><input type="radio" name="wp_review_comment_rating" id="rating" value="'. $i .'"/>'. $i .'</span>'; echo'</span></p>'; } // Save the comment metadata along with the comment. add_action( 'comment_post', 'save_comment_meta_data' ); function save_comment_meta_data( $comment_id ) { if ( ( isset( $_POST['wp_review_comment_title'] ) ) && ( $_POST['wp_review_comment_title'] != '') ) $title = wp_filter_nohtml_kses($_POST['wp_review_comment_title']); add_comment_meta( $comment_id, 'wp_review_comment_title', $title ); if ( ( isset( $_POST['wp_review_comment_rating'] ) ) && ( $_POST['wp_review_comment_rating'] != '') ) $rating = wp_filter_nohtml_kses($_POST['wp_review_comment_rating']); add_comment_meta( $comment_id, 'wp_review_comment_rating', $rating ); } // Check if the comment metadata has been filled or not add_filter( 'preprocess_comment', 'verify_comment_meta_data' ); function verify_comment_meta_data( $commentdata ) { if ( ! isset( $_POST['wp_review_comment_rating'] ) ) wp_die( __( 'A rating is requird. Hit the BACK button and resubmit your review with a rating.' ) ); return $commentdata; } ``` Now, my comments are saved as default comment-type="comment". How do I save the comment as a custom comment type "wp\_review\_comment"?
In addition. You already have code which can kind of do what you need. ``` add_filter( 'preprocess_comment', 'verify_comment_meta_data' ); function verify_comment_meta_data( $commentdata ) { if ( ! isset( $_POST['wp_review_comment_rating'] ) ) wp_die( __( 'A rating is required. Hit the BACK button and resubmit your review with a rating.' ) ); // this is filter and $commentdata has comment_type parameter in it. so you need to do this $commentdata['comment_type'] = 'wp_review_comment'; return $commentdata; } ``` This will do what you wanted but now all your newly created comments will become this type of `wp_review_comment`, so if you need them the other way - you'll need some kind of conditionals in this filter instead of forcing all comments to have `wp_review_comment_rating` and forcing them to be `wp_review_comment` type or die(), preventing from saving. See <https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/comment.php#L1874> for more details
360,279
<p>I have a plugin that implements a REST API that needs to be notified when an admin adds one of my supported shortcodes to a page or post. I hook save_post with my function like this.</p> <pre><code> add_action( 'save_post', 'detect_shortcodes'); </code></pre> <p>However, when I update from the editor, it does an ajax call that instantiates my plugin. The first thing it does is determine whether to load public or admin hooks like this.</p> <pre><code> if(is_admin()) { $this-&gt;define_admin_hooks(); } else { $this-&gt;define_public_hooks(); } </code></pre> <p>Of course, my detect_shortcodes function is on the admin side. With the TinyMCE editor, this worked correctly, and instantiated my admin hooks. With the Gutenberg editor, is_admin() returns false.</p> <p>Is there a replacement for is_admin() that will work with Gutenberg ajax calls?</p>
[ { "answer_id": 360288, "author": "BenB", "author_id": 62909, "author_profile": "https://wordpress.stackexchange.com/users/62909", "pm_score": 0, "selected": false, "text": "<p>I think this hook should work:</p>\n\n<pre><code>function run_hooks( $post, $request ) {\n // Here you can run your hooks\n}\nadd_action('rest_after_insert_post', 'run_hooks', 10, 2);\n</code></pre>\n" }, { "answer_id": 360328, "author": "AldenG", "author_id": 183987, "author_profile": "https://wordpress.stackexchange.com/users/183987", "pm_score": 0, "selected": false, "text": "<p>I have landed on this embarrassing hack. I hope someone can improve this answer and make it less brittle. Perhaps read taxonomy to find current pages and posts endpoints?</p>\n\n<pre><code> $pagesajax = 'wp-json/wp/v2/pages';\n $postsajax = 'wp-json/wp/v2/posts';\n\n if(is_admin() || !empty($_SERVER['REQUEST_URI']) &amp;&amp;\n strpos($_SERVER['REQUEST_URI'], $pagesajax) !== false ||\n strpos($_SERVER['REQUEST_URI'], $postsajax) !== false)\n {\n ... load admin side ...\n }\n</code></pre>\n" }, { "answer_id": 367515, "author": "chifliiiii", "author_id": 4130, "author_profile": "https://wordpress.stackexchange.com/users/4130", "pm_score": 2, "selected": false, "text": "<p>You could try with the following instead to detect if rest</p>\n\n<pre><code>if ( is_admin() || defined( 'REST_REQUEST' ) &amp;&amp; REST_REQUEST ) {\n\n}\n</code></pre>\n" } ]
2020/03/08
[ "https://wordpress.stackexchange.com/questions/360279", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183987/" ]
I have a plugin that implements a REST API that needs to be notified when an admin adds one of my supported shortcodes to a page or post. I hook save\_post with my function like this. ``` add_action( 'save_post', 'detect_shortcodes'); ``` However, when I update from the editor, it does an ajax call that instantiates my plugin. The first thing it does is determine whether to load public or admin hooks like this. ``` if(is_admin()) { $this->define_admin_hooks(); } else { $this->define_public_hooks(); } ``` Of course, my detect\_shortcodes function is on the admin side. With the TinyMCE editor, this worked correctly, and instantiated my admin hooks. With the Gutenberg editor, is\_admin() returns false. Is there a replacement for is\_admin() that will work with Gutenberg ajax calls?
You could try with the following instead to detect if rest ``` if ( is_admin() || defined( 'REST_REQUEST' ) && REST_REQUEST ) { } ```
360,372
<p>I need a function to redirect user to the plugin settings page, right after plugin activation. </p> <p>I use this function to create a custom menu settings page:</p> <pre><code>// add option page menu link function axl_ads_add_admin_menu() { $icon = 'dashicons-align-left"'; add_menu_page( 'AXL Ads', 'AXL Ads', 'manage_options', 'axl_ads', array($this, 'axl_ads_options_page'), $icon, '3' ); } </code></pre> <p>And my settings page url is: <code>wp-admin/admin.php?page=axl_ads</code></p> <p>Any help with this, please?</p>
[ { "answer_id": 360391, "author": "Zakaria Binsaifullah", "author_id": 158754, "author_profile": "https://wordpress.stackexchange.com/users/158754", "pm_score": 0, "selected": false, "text": "<p>There is a hook named register_activation_hook that usually works at the time of the plugin activation. This function should be called within the plugins_loaded hook. So,</p>\n\n<p>Firstly, call the activation hook - </p>\n\n<pre><code>function fn_name(){\nregister_activation_hook(__FILE__,'activation_fn');\n}\nadd_action('plugins_loaded','fn_name');\n</code></pre>\n\n<p>Now, you need to call the function - </p>\n\n<pre><code>function activation_fn(){\n wp_redirect($target_url);\n}\n</code></pre>\n\n<p>here, wp_redirect($url) is used that redirect you to a specific location. So, simply add your target URL inside the wp_redirect() function. </p>\n\n<p>As a result, when your plugin will be activated, it will automatically redirect to you to the specific location.</p>\n" }, { "answer_id": 360392, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 2, "selected": true, "text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/register_activation_hook/\" rel=\"nofollow noreferrer\">register_activation_hook()</a>. Add this to your plugin, tested and works.</p>\n\n<pre><code>register_activation_hook(__FILE__, 'redirect_after_activation');\n\nfunction redirect_after_activation() {\n add_option('redirect_after_activation_option', true);\n}\n\nadd_action('admin_init', 'activation_redirect');\n\nfunction activation_redirect() {\n if (get_option('redirect_after_activation_option', false)) {\n delete_option('redirect_after_activation_option');\n exit(wp_redirect(admin_url( 'wp-admin/admin.php?page=axl_ads' )));\n }\n}\n</code></pre>\n" } ]
2020/03/10
[ "https://wordpress.stackexchange.com/questions/360372", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33903/" ]
I need a function to redirect user to the plugin settings page, right after plugin activation. I use this function to create a custom menu settings page: ``` // add option page menu link function axl_ads_add_admin_menu() { $icon = 'dashicons-align-left"'; add_menu_page( 'AXL Ads', 'AXL Ads', 'manage_options', 'axl_ads', array($this, 'axl_ads_options_page'), $icon, '3' ); } ``` And my settings page url is: `wp-admin/admin.php?page=axl_ads` Any help with this, please?
You can use [register\_activation\_hook()](https://developer.wordpress.org/reference/functions/register_activation_hook/). Add this to your plugin, tested and works. ``` register_activation_hook(__FILE__, 'redirect_after_activation'); function redirect_after_activation() { add_option('redirect_after_activation_option', true); } add_action('admin_init', 'activation_redirect'); function activation_redirect() { if (get_option('redirect_after_activation_option', false)) { delete_option('redirect_after_activation_option'); exit(wp_redirect(admin_url( 'wp-admin/admin.php?page=axl_ads' ))); } } ```
360,377
<p>I am new to Wordpress and following a training course. Its told me to enable to use of Featured Images I need to add the following line into my functions.php:</p> <pre class="lang-php prettyprint-override"><code>add_theme_support('post-thumbnails'); </code></pre> <p>and then the following in my post types file:</p> <pre class="lang-php prettyprint-override"><code> 'supports' =&gt; array('title', 'editor', 'thumbnail'), </code></pre> <p>However I have done this but no luck getting the option to add a featured image. I have checked screen options and it is not appearing as an option I can enable. </p> <p>I've checked similar threads already but no luck :(</p>
[ { "answer_id": 360378, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 2, "selected": true, "text": "<p>That one line is all you need, try adding this to your functions.php file.</p>\n\n<pre><code>function my_theme_setup(){\n add_theme_support('post-thumbnails');\n}\n\nadd_action('after_setup_theme', 'my_theme_setup');\n</code></pre>\n\n<p>I'm not sure what your \"post types file\" is but the above should be enough to add support.</p>\n" }, { "answer_id": 360380, "author": "Wacław Jacek", "author_id": 115216, "author_profile": "https://wordpress.stackexchange.com/users/115216", "pm_score": 0, "selected": false, "text": "<p>This is how it should look like in your theme's <code>functions.php</code> file:</p>\n\n<pre><code>&lt;?php\n\n/* Register thumbnail support */\n\nadd_action( 'after_setup_theme', 'my_theme_register_thumbnail_support' );\nfunction my_theme_register_thumbnail_support() {\n add_theme_support( 'post-thumbnails' );\n}\n\n/* Register the custom post type */\n\nadd_action( 'init', 'my_theme_register_custom_post_type' );\nfunction my_theme_register_custom_post_type() {\n register_post_type( 'my_post_type', array(\n 'label' =&gt; 'My Post Type',\n 'supports' =&gt; array( 'title', 'editor', 'thumbnail' ),\n ) );\n}\n</code></pre>\n" }, { "answer_id": 360389, "author": "Zakaria Binsaifullah", "author_id": 158754, "author_profile": "https://wordpress.stackexchange.com/users/158754", "pm_score": 0, "selected": false, "text": "<p>You have right everything ok. Just you need to ensure that you have call the function inside init or after_setup_theme hook in the functions.php. It will look like the following codes- </p>\n\n<pre><code>function fn_name(){\n add_theme_support('post-thumbnails');\n}\nadd_action('after_setup_theme','fn_name');\n</code></pre>\n\n<p>or </p>\n\n<pre><code>function fn_name(){\n add_theme_support('post-thumbnails');\n}\nadd_action('init','fn_name');\n</code></pre>\n\n<p>and finally, ensure that thumbnail is supported in your CPT.</p>\n" } ]
2020/03/10
[ "https://wordpress.stackexchange.com/questions/360377", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/184073/" ]
I am new to Wordpress and following a training course. Its told me to enable to use of Featured Images I need to add the following line into my functions.php: ```php add_theme_support('post-thumbnails'); ``` and then the following in my post types file: ```php 'supports' => array('title', 'editor', 'thumbnail'), ``` However I have done this but no luck getting the option to add a featured image. I have checked screen options and it is not appearing as an option I can enable. I've checked similar threads already but no luck :(
That one line is all you need, try adding this to your functions.php file. ``` function my_theme_setup(){ add_theme_support('post-thumbnails'); } add_action('after_setup_theme', 'my_theme_setup'); ``` I'm not sure what your "post types file" is but the above should be enough to add support.
360,379
<pre><code>&lt;?php global $current_user; echo array_shift($current_user-&gt;roles);&gt; </code></pre> <p>Using this i can display user role slug but i want to display Name of the role. Any suggestion ? Thanks</p>
[ { "answer_id": 360384, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 4, "selected": true, "text": "<p>WordPress does not (currently) have a <em>global</em> function (e.g. <code>get_role_name()</code>) for getting the role <em>name</em> (e.g. <code>Shop Manager</code> for <code>shop-manager</code> or maybe <code>shop_manager</code> etc.), but you can easily get (and then display) it like so:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$role = 'shop-manager'; // the role slug; it's up to you how to get the value..\n\n$role_name = $role ? wp_roles()-&gt;get_names()[ $role ] : '';\n/* Or directly access WP_Roles::$role_names:\n$role_name = $role ? wp_roles()-&gt;role_names[ $role ] : '';\n*/\n\necho $role_name;\n</code></pre>\n\n<p>References: <a href=\"https://developer.wordpress.org/reference/functions/wp_roles/\" rel=\"nofollow noreferrer\"><code>wp_roles()</code></a> and the <a href=\"https://developer.wordpress.org/reference/classes/wp_roles/\" rel=\"nofollow noreferrer\"><code>WP_Roles</code> class</a>.</p>\n\n<h3>Some Additional Notes</h3>\n\n<ol>\n<li><p>Be careful when using <code>array_shift()</code> - it does return the value but also removes the original item from the source array, so in your case, the next time you access <code>$current_user-&gt;roles</code>, it would be empty or no longer contains the user's role.</p></li>\n<li><p>Just as with the current <em>post</em> where it's a better practice to access the post object/data using <code>get_post()</code>, it's also recommended to use <a href=\"https://developer.wordpress.org/reference/functions/wp_get_current_user/\" rel=\"nofollow noreferrer\"><code>wp_get_current_user()</code></a> to get the current user object/data instead of relying upon the global <code>$current_user</code> variable.</p>\n\n<p>And if your code runs only if the current user is authenticated/logged-in, then a shortcut for getting the user role is <code>$role = wp_get_current_user()-&gt;roles[0];</code> :)</p></li>\n</ol>\n\n<p><em>PS: Big thanks to <a href=\"https://wordpress.stackexchange.com/users/115216/wac%c5%82aw-jacek\">@WacławJacek</a> for his helpful comment! =)</em></p>\n" }, { "answer_id": 360385, "author": "g3ar", "author_id": 164836, "author_profile": "https://wordpress.stackexchange.com/users/164836", "pm_score": 1, "selected": false, "text": "<pre><code>&lt;?php\nglobal $current_user;\n$role = $current_user-&gt;roles[0];\n$role_name = $role ? wp_roles()-&gt;get_names()[ $role ] : '';\necho $role_name;\n?&gt;\n</code></pre>\n\n<p>Works like a charm</p>\n" } ]
2020/03/10
[ "https://wordpress.stackexchange.com/questions/360379", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/164836/" ]
``` <?php global $current_user; echo array_shift($current_user->roles);> ``` Using this i can display user role slug but i want to display Name of the role. Any suggestion ? Thanks
WordPress does not (currently) have a *global* function (e.g. `get_role_name()`) for getting the role *name* (e.g. `Shop Manager` for `shop-manager` or maybe `shop_manager` etc.), but you can easily get (and then display) it like so: ```php $role = 'shop-manager'; // the role slug; it's up to you how to get the value.. $role_name = $role ? wp_roles()->get_names()[ $role ] : ''; /* Or directly access WP_Roles::$role_names: $role_name = $role ? wp_roles()->role_names[ $role ] : ''; */ echo $role_name; ``` References: [`wp_roles()`](https://developer.wordpress.org/reference/functions/wp_roles/) and the [`WP_Roles` class](https://developer.wordpress.org/reference/classes/wp_roles/). ### Some Additional Notes 1. Be careful when using `array_shift()` - it does return the value but also removes the original item from the source array, so in your case, the next time you access `$current_user->roles`, it would be empty or no longer contains the user's role. 2. Just as with the current *post* where it's a better practice to access the post object/data using `get_post()`, it's also recommended to use [`wp_get_current_user()`](https://developer.wordpress.org/reference/functions/wp_get_current_user/) to get the current user object/data instead of relying upon the global `$current_user` variable. And if your code runs only if the current user is authenticated/logged-in, then a shortcut for getting the user role is `$role = wp_get_current_user()->roles[0];` :) *PS: Big thanks to [@WacławJacek](https://wordpress.stackexchange.com/users/115216/wac%c5%82aw-jacek) for his helpful comment! =)*
360,407
<p>there is this loop which sorts by the date. But I want to throw in a specific meta key for a even higher priority. The meta_key "high_prio" should move it to the top of the sorting. (I hope that makes sence). </p> <p>Let's speak some code:</p> <pre><code>$loop = new WP_Query( array( 'post_type' =&gt; 'event', 'posts_per_page' =&gt; 3, 'cat' =&gt; '4', 'orderby' =&gt; array( 'meta_start' =&gt; 'ASC','meta_prio' =&gt; 'DESC'), 'meta_query' =&gt; array( 'relation' =&gt; 'OR', 'meta_start' =&gt; array( 'key' =&gt; 'date_start', 'type' =&gt; 'numeric' ), 'meta_prio' =&gt; array( 'key' =&gt; 'high_prio', 'type' =&gt; 'numeric' ) ) )); </code></pre> <p>The SQL looks like this now:</p> <pre><code>SELECT SQL_CALC_FOUND_ROWS pdh50NA5_posts.ID FROM pdh50NA5_posts LEFT JOIN pdh50NA5_term_relationships ON (pdh50NA5_posts.ID = pdh50NA5_term_relationships.object_id) INNER JOIN pdh50NA5_postmeta ON ( pdh50NA5_posts.ID = pdh50NA5_postmeta.post_id ) WHERE 1=1 AND ( pdh50NA5_term_relationships.term_taxonomy_id IN (4) ) AND ( pdh50NA5_postmeta.meta_key = 'date_start' OR pdh50NA5_postmeta.meta_key = 'high_prio' ) AND pdh50NA5_posts.post_type = 'event' AND (pdh50NA5_posts.post_status = 'publish' OR pdh50NA5_posts.post_status = 'acf-disabled' OR pdh50NA5_posts.post_status = 'private') GROUP BY pdh50NA5_posts.ID ORDER BY CAST(pdh50NA5_postmeta.meta_value AS SIGNED) ASC, CAST(pdh50NA5_postmeta.meta_value AS SIGNED) DESC LIMIT 0, 3 </code></pre> <p>I am not good at SQL. I understand the basics but the <strong>order</strong> part is too much.</p> <p>Maybe this has to be done differently. Thanks in advance! </p>
[ { "answer_id": 360529, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 1, "selected": false, "text": "<p>As I already pointed in the comment, all you need to do is change your <code>orderby</code> parameter so that the <code>meta_prio</code> is the first item and followed by the <code>meta_start</code>. So your <code>orderby</code> should look like:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// This array forms an ORDER BY clause with each array item being a column that\n// MySQL use when sorting the posts/results.\n'orderby' =&gt; array(\n // This is the first column, which has the highest priority and sorts by the\n // meta high_prio.\n 'meta_prio' =&gt; 'DESC',\n\n // This is the second column, which sorts by the meta date_start, after MySQL\n // sort the results by the meta high_prio.\n 'meta_start' =&gt; 'ASC',\n)\n</code></pre>\n\n<p>So with the above example, the generated <code>ORDER BY</code> clause would look something like <code>ORDER BY &lt;meta_prio column&gt; DESC, &lt;meta_start column&gt; ASC</code> and MySQL would first sort the results by the <code>high_prio</code> meta and then sort the <strong>sorted</strong> results by the <code>date_start</code> meta.</p>\n\n<p>And remember that the <em>array key</em> used in your <code>orderby</code> must match the one in your <code>meta_query</code>, if you're sorting the results by the meta query clauses in the <code>meta_query</code> array. Additionally, make sure you set the proper <code>type</code> in your meta query clauses; e.g. if the value is a date like <code>2020-03-12 09:30</code>, then you'd set the type to <code>DATETIME</code> (i.e. <code>'type' =&gt; 'DATETIME'</code>):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>'meta_query' =&gt; array(\n 'relation' =&gt; 'OR',\n 'meta_start' =&gt; array(\n 'key' =&gt; 'date_start',\n 'type' =&gt; 'DATETIME',\n ),\n 'meta_prio' =&gt; array(\n 'key' =&gt; 'high_prio',\n 'type' =&gt; 'NUMERIC',\n )\n),\n// Make sure the array keys match those in the above meta_query array.\n'orderby' =&gt; array(\n 'meta_prio' =&gt; 'DESC',\n 'meta_start' =&gt; 'ASC',\n),\n</code></pre>\n" }, { "answer_id": 360825, "author": "Marv", "author_id": 184095, "author_profile": "https://wordpress.stackexchange.com/users/184095", "pm_score": -1, "selected": true, "text": "<p>The issue has been the <strong>relation</strong>. Of course, it must be \"AND\"</p>\n\n<pre><code>$loop = new WP_Query( array(\n 'post_type' =&gt; 'event',\n 'posts_per_page' =&gt; 3,\n 'cat' =&gt; '4',\n 'orderby' =&gt; array('meta_prio' =&gt; 'DESC', 'meta_start' =&gt; 'ASC'),\n 'meta_query' =&gt; array(\n 'relation' =&gt; '**AND**',\n 'meta_start' =&gt; array(\n 'key' =&gt; 'date_start',\n 'type' =&gt; 'numeric'\n ),\n 'meta_prio' =&gt; array(\n 'key' =&gt; 'high_prio',\n 'type' =&gt; 'numeric'\n )\n )\n ));\n</code></pre>\n" } ]
2020/03/10
[ "https://wordpress.stackexchange.com/questions/360407", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/184095/" ]
there is this loop which sorts by the date. But I want to throw in a specific meta key for a even higher priority. The meta\_key "high\_prio" should move it to the top of the sorting. (I hope that makes sence). Let's speak some code: ``` $loop = new WP_Query( array( 'post_type' => 'event', 'posts_per_page' => 3, 'cat' => '4', 'orderby' => array( 'meta_start' => 'ASC','meta_prio' => 'DESC'), 'meta_query' => array( 'relation' => 'OR', 'meta_start' => array( 'key' => 'date_start', 'type' => 'numeric' ), 'meta_prio' => array( 'key' => 'high_prio', 'type' => 'numeric' ) ) )); ``` The SQL looks like this now: ``` SELECT SQL_CALC_FOUND_ROWS pdh50NA5_posts.ID FROM pdh50NA5_posts LEFT JOIN pdh50NA5_term_relationships ON (pdh50NA5_posts.ID = pdh50NA5_term_relationships.object_id) INNER JOIN pdh50NA5_postmeta ON ( pdh50NA5_posts.ID = pdh50NA5_postmeta.post_id ) WHERE 1=1 AND ( pdh50NA5_term_relationships.term_taxonomy_id IN (4) ) AND ( pdh50NA5_postmeta.meta_key = 'date_start' OR pdh50NA5_postmeta.meta_key = 'high_prio' ) AND pdh50NA5_posts.post_type = 'event' AND (pdh50NA5_posts.post_status = 'publish' OR pdh50NA5_posts.post_status = 'acf-disabled' OR pdh50NA5_posts.post_status = 'private') GROUP BY pdh50NA5_posts.ID ORDER BY CAST(pdh50NA5_postmeta.meta_value AS SIGNED) ASC, CAST(pdh50NA5_postmeta.meta_value AS SIGNED) DESC LIMIT 0, 3 ``` I am not good at SQL. I understand the basics but the **order** part is too much. Maybe this has to be done differently. Thanks in advance!
The issue has been the **relation**. Of course, it must be "AND" ``` $loop = new WP_Query( array( 'post_type' => 'event', 'posts_per_page' => 3, 'cat' => '4', 'orderby' => array('meta_prio' => 'DESC', 'meta_start' => 'ASC'), 'meta_query' => array( 'relation' => '**AND**', 'meta_start' => array( 'key' => 'date_start', 'type' => 'numeric' ), 'meta_prio' => array( 'key' => 'high_prio', 'type' => 'numeric' ) ) )); ```